serialization: move serialization_core
[nit.git] / lib / serialization / engine_tools.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Advanced services for serialization engines
16 module engine_tools
17
18 import serialization_core
19 intrude import core::collection::hash_collection
20
21 # Maps instances to a value, uses `is_same_serialized` and `serialization_hash`.
22 class StrictHashMap[K, V]
23 super HashMap[K, V]
24
25 redef fun index_at(k)
26 do
27 if k == null then return 0
28
29 var i = k.serialization_hash % _capacity
30 if i < 0 then i = - i
31 return i
32 end
33
34 redef fun node_at_idx(i, k)
35 do
36 var c = _array[i]
37 while c != null do
38 var ck = c._key
39 assert ck != null
40 if ck.is_same_serialized(k) then
41 break
42 end
43 c = c._next_in_bucklet
44 end
45 return c
46 end
47 end
48
49 redef interface Object
50 # Is `self` the same as `other` in a serialization context?
51 #
52 # Used to determine if an object has already been serialized.
53 fun is_same_serialized(other: nullable Object): Bool do return is_same_instance(other)
54
55 # Hash value use for serialization
56 #
57 # Used in combination with `is_same_serialized`. If two objects are the same
58 # in a serialization context, they must have the same `serialization_hash`.
59 fun serialization_hash: Int do return object_id
60 end
61
62 redef class Text
63
64 # Strip the `nullable` prefix from the type name `self`
65 #
66 # ~~~
67 # assert "String".strip_nullable == "String"
68 # assert "nullable Array[Int]".strip_nullable == "Array[Int]"
69 # assert "Map[Set[String], Set[Int]]".strip_nullable == "Map[Set[String], Set[Int]]"
70 # ~~~
71 fun strip_nullable: Text
72 do
73 var prefix = "nullable "
74 return if has_prefix(prefix) then substring_from(prefix.length) else self
75 end
76
77 # Strip the `nullable` prefix and the params from the type name `self`
78 #
79 # ~~~
80 # assert "String".strip_nullable_and_params == "String"
81 # assert "nullable Array[Int]".strip_nullable_and_params == "Array"
82 # assert "Map[Set[String], Set[Int]]".strip_nullable_and_params == "Map"
83 # ~~~
84 fun strip_nullable_and_params: Text
85 do
86 var class_name = strip_nullable
87
88 var bracket_index = class_name.index_of('[')
89 if bracket_index == -1 then return class_name
90 return class_name.substring(0, bracket_index)
91 end
92 end