9
9
10
10
# # Nim OID support. An OID is a global ID that consists of a timestamp,
11
11
# # a unique counter and a random value. This combination should suffice to
12
- # # produce a globally distributed unique ID. This implementation was extracted
13
- # # from the MongoDB interface and is thus binary compatible with a MongoDB OID.
12
+ # # produce a globally distributed unique ID.
14
13
# #
15
14
# # This implementation calls `initRand()` for the first call of
16
15
# # `genOid`.
@@ -20,7 +19,7 @@ from std/private/decode_helpers import handleHexChar
20
19
21
20
type
22
21
Oid * = object # # An OID.
23
- time: int32
22
+ time: int64
24
23
fuzz: int32
25
24
count: int32
26
25
@@ -44,37 +43,27 @@ proc parseOid*(str: cstring): Oid =
44
43
# # Parses an OID.
45
44
var bytes = cast [cstring ](addr (result .time))
46
45
var i = 0
47
- while i < 12 :
46
+ while i < 16 :
48
47
bytes[i] = chr ((hexbyte (str[2 * i]) shl 4 ) or hexbyte (str[2 * i + 1 ]))
49
48
inc (i)
50
49
51
- template toStringImpl [T: string | cstring ](result: var T, oid: Oid ) =
52
- # # Stringifies `oid` .
50
+ proc `$` * ( oid: Oid ): string =
51
+ # # Converts an OID to a string .
53
52
const hex = " 0123456789abcdef"
54
- const N = 24
55
53
56
- when T is string :
57
- result .setLen N
54
+ result .setLen 32
58
55
59
56
var o = oid
60
57
var bytes = cast [cstring ](addr (o))
61
58
var i = 0
62
- while i < 12 :
59
+ while i < 16 :
63
60
let b = bytes[i].ord
64
61
result [2 * i] = hex[(b and 0x F0 ) shr 4 ]
65
62
result [2 * i + 1 ] = hex[b and 0x F ]
66
63
inc (i)
67
- when T is cstring :
68
- result [N] = '\0 '
69
-
70
-
71
- proc `$` * (oid: Oid ): string =
72
- # # Converts an OID to a string.
73
- toStringImpl (result , oid)
74
-
75
64
76
65
let
77
- t = getTime ().toUnix. int32
66
+ t = getTime ().toUnix
78
67
79
68
var
80
69
seed = initRand (t)
@@ -84,24 +73,24 @@ let fuzz = cast[int32](seed.rand(high(int)))
84
73
85
74
86
75
template genOid (result: var Oid , incr: var int , fuzz: int32 ) =
87
- var time = getTime ().toUnix. int32
76
+ var time = getTime ().toUnix
88
77
var i = cast [int32 ](atomicInc (incr))
89
78
90
- bigEndian32 (addr result .time, addr (time))
79
+ bigEndian64 (addr result .time, addr (time))
91
80
result .fuzz = fuzz
92
81
bigEndian32 (addr result .count, addr (i))
93
82
94
83
proc genOid * (): Oid =
95
84
# # Generates a new OID.
96
85
runnableExamples:
97
- doAssert ($ genOid ()).len == 24
86
+ doAssert ($ genOid ()).len == 32
98
87
runnableExamples (" -r:off" ):
99
- echo $ genOid () # for example, "5fc7f546ddbbc84800006aaf "
88
+ echo $ genOid () # for example, "00000000632c452db08c3d19ee9073e5 "
100
89
genOid (result , incr, fuzz)
101
90
102
91
proc generatedTime * (oid: Oid ): Time =
103
92
# # Returns the generated timestamp of the OID.
104
- var tmp: int32
93
+ var tmp: int64
105
94
var dummy = oid.time
106
- bigEndian32 (addr (tmp), addr (dummy))
95
+ bigEndian64 (addr (tmp), addr (dummy))
107
96
result = fromUnix (tmp)
0 commit comments