Skip to content

Commit 0070aee

Browse files
committed
Make CSUUID able to use PCG32 in addition to ISAAC. It seems that ISAAC has a bug, and in some scenarios, simply instantiating it will cause really fun GC problems.
1 parent 3d7ae5f commit 0070aee

File tree

4 files changed

+20
-6
lines changed

4 files changed

+20
-6
lines changed

Diff for: shard.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name: csuuid
2-
version: 0.3.1
2+
version: 0.4.0
33

44
authors:
55
- Kirk Haines <[email protected]>

Diff for: spec/csuuid_spec.cr

+11
Original file line numberDiff line numberDiff line change
@@ -129,4 +129,15 @@ describe CSUUID do
129129
(uuid2 >= uuid1).should be_true
130130
(uuid1 >= uuid1).should be_true
131131
end
132+
133+
it "can work with PCG32 as the generator" do
134+
CSUUID.prng = Random::PCG32.new
135+
uuid1 = CSUUID.unique
136+
uuid2 = CSUUID.unique
137+
CHECKUUID.match(uuid1.to_s).should_not be_nil
138+
CHECKUUID.match(uuid2.to_s).should_not be_nil
139+
uuid1.should_not eq uuid2
140+
uuid2.should be > uuid1
141+
end
142+
132143
end

Diff for: spec/spec_helper.cr

+2
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ require "spec"
22
require "../src/csuuid"
33
require "parse_date"
44
require "benchmark"
5+
require "random/pcg32"
6+
require "random/secure"

Diff for: src/csuuid.cr

+6-5
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,12 @@ require "crystal/spin_lock"
3939
# +-------------+-----------------+------------+
4040
# ```
4141
#
42+
4243
struct CSUUID
43-
VERSION = "0.3.1"
44+
VERSION = "0.4.0"
4445

46+
class_property prng : Random::ISAAC | Random::PCG32 = Random::ISAAC.new
4547
@@mutex = Crystal::SpinLock.new
46-
@@prng = Random::ISAAC.new
4748
@@unique_identifier : Slice(UInt8) = Slice(UInt8).new(6, 0)
4849
@@unique_seconds_and_nanoseconds : Tuple(Int64, Int32) = {0_i64, 0_i32}
4950

@@ -62,7 +63,7 @@ struct CSUUID
6263
increment_unique_identifier
6364
else
6465
@@unique_seconds_and_nanoseconds = {t.internal_seconds, t.internal_nanoseconds}
65-
@@unique_identifier = @@prng.random_bytes(6)
66+
@@unique_identifier = prng.random_bytes(6)
6667
end
6768

6869
new(
@@ -107,7 +108,7 @@ struct CSUUID
107108
end
108109

109110
def initialize(identifier : Slice(UInt8) | String | Nil = nil)
110-
identifier ||= @@prng.random_bytes(6)
111+
identifier ||= CSUUID.prng.random_bytes(6)
111112
t = Time.local
112113
initialize_impl(t.internal_seconds, t.internal_nanoseconds, identifier)
113114
end
@@ -128,7 +129,7 @@ struct CSUUID
128129
# Random::ISAAC.random_bytes doesn't appear to be threadsafe.
129130
# It sometimes dies ugly in multithreaded code, so we need a
130131
# lock in this one tiny little space to avoid that.
131-
@bytes[10, 6].copy_from(id || @@prng.random_bytes(6))
132+
@bytes[10, 6].copy_from(id || CSUUID.prng.random_bytes(6))
132133
end
133134
end
134135

0 commit comments

Comments
 (0)