File: string_pool_spec.cr

package info (click to toggle)
crystal 1.6.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 18,956 kB
  • sloc: javascript: 1,712; sh: 592; cpp: 541; makefile: 243; ansic: 119; python: 105; xml: 32
file content (92 lines) | stat: -rw-r--r-- 1,880 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require "spec"
require "string_pool"

describe StringPool do
  it "is empty" do
    pool = StringPool.new
    pool.empty?.should be_true
    pool.size.should eq(0)
  end

  it "gets string" do
    pool = StringPool.new
    s1 = pool.get "foo"
    s2 = pool.get "foo"

    s1.should eq("foo")
    s2.should eq("foo")
    s1.should be(s2)
    pool.size.should eq(1)
  end

  it "gets string IO" do
    pool = StringPool.new
    io = IO::Memory.new "foo"

    s1 = pool.get io
    s2 = pool.get "foo"

    s1.should eq("foo")
    s2.should eq("foo")
    s1.should be(s2)
    pool.size.should eq(1)
  end

  it "gets slice" do
    pool = StringPool.new
    slice = Bytes.new(3, 'a'.ord.to_u8)

    s1 = pool.get(slice)
    s2 = pool.get(slice)

    s1.should eq("aaa")
    s2.should eq("aaa")
    s1.should be(s2)
    pool.size.should eq(1)
  end

  it "gets pointer with size" do
    pool = StringPool.new
    slice = Bytes.new(3, 'a'.ord.to_u8)

    s1 = pool.get(slice.to_unsafe, slice.size)
    s2 = pool.get(slice.to_unsafe, slice.size)

    s1.should eq("aaa")
    s2.should eq("aaa")
    s1.should be(s2)
    pool.size.should eq(1)
  end

  it "puts many" do
    pool = StringPool.new
    10_000.times do |i|
      pool.get(i.to_s)
    end
    pool.size.should eq(10_000)
  end

  it "can be created with larger initial capacity" do
    pool = StringPool.new(initial_capacity: 32)
    s1 = pool.get "foo"
    s2 = pool.get "foo"
    s1.should be(s2)
    pool.size.should eq(1)
  end

  it "doesn't fail if initial capacity is too small" do
    pool = StringPool.new(initial_capacity: 0)
    100.times do |i|
      pool.get(i.to_s)
    end
    pool.size.should eq(100)
  end

  it "doesn't fail if initial capacity is not a power of 2" do
    pool = StringPool.new(initial_capacity: 17)
    100.times do |i|
      pool.get(i.to_s)
    end
    pool.size.should eq(100)
  end
end