neo4j/graph: Optimize some services of `SequentialNodeCollection`.
[nit.git] / lib / neo4j / graph / sequential_id.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Provides a sequential identification scheme for Neo4j nodes.
12 module neo4j::graph::sequential_id
13
14 import graph
15 private import pipeline
16
17
18 # A Neo4j node collection using a sequential identification scheme.
19 #
20 # The local IDs are sequential numbers (integers) starting at `1`.
21 #
22 # Note: When loading nodes, the local IDs should forms a mostly contiguous
23 # range starting at `1`. Else, this collection will consume a lot of memory.
24 # Futhermore, the local IDs **must** be positive.
25 #
26 # ~~~nit
27 # var nodes = new SequentialNodeCollection("id")
28 # var a = nodes.create_node
29 # var b = new NeoNode
30 # var c = new NeoNode
31 #
32 # nodes.register b
33 # c["id"] = 4
34 # nodes.add c
35 # assert a["id"] == 1
36 # assert b["id"] == 2
37 # assert c["id"] == 4
38 # assert nodes.to_a == [a, b, c]
39 # assert nodes.length == 3
40 # ~~~
41 class SequentialNodeCollection
42 super NeoNodeCollection
43
44 redef type ID_TYPE: Int
45
46 private var nodes = new Array[nullable NeoNode]
47
48 redef var length = 0
49
50 redef fun iterator do return new NullSkipper[NeoNode](self.nodes.iterator)
51
52 redef fun [](id) do return nodes[id].as(NeoNode)
53
54 redef fun get_or_null(id) do
55 if id < 0 or id > nodes.length then return null
56 return nodes[id]
57 end
58
59 redef fun has_id(id: Int): Bool do
60 return id >= 0 and id < nodes.length and nodes[id] isa NeoNode
61 end
62
63 redef fun register(node) do
64 nodes.add node
65 id_of(node) = nodes.length
66 length += 1
67 end
68
69 redef fun add(node) do
70 var id = node[id_property]
71 assert id isa Int else
72 sys.stderr.write "The local ID must be an `Int`.\n"
73 end
74 assert id >= 0 else
75 sys.stderr.write "The local ID must be greater or equal to 0. Got {id}.\n"
76 end
77 # Pad with nulls.
78 nodes.enlarge(id)
79 var delta = id - nodes.length
80 while delta > 0 do
81 nodes.add null
82 delta -= 1
83 end
84 nodes[id] = node
85 length += 1
86 end
87
88 redef fun remove_at(id) do
89 nodes[id] = null
90 length -= 1
91 end
92
93 redef fun clear do
94 nodes.clear
95 length = 0
96 end
97 end