| 1 |
# frozen_string_literal: true |
| 2 |
require 'test/unit' |
| 3 |
require '-test-/string' |
| 4 |
require 'rbconfig/sizeof' |
| 5 |
|
| 6 |
class Test_StringCapacity < Test::Unit::TestCase |
| 7 |
def test_capacity_embedded |
| 8 |
assert_equal GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE] - embed_header_size - 1, capa('foo') |
| 9 |
assert_equal max_embed_len, capa('1' * max_embed_len) |
| 10 |
assert_equal max_embed_len, capa('1' * (max_embed_len - 1)) |
| 11 |
end |
| 12 |
|
| 13 |
def test_capacity_shared |
| 14 |
sym = ("a" * GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE]).to_sym |
| 15 |
assert_equal 0, capa(sym.to_s) |
| 16 |
end |
| 17 |
|
| 18 |
def test_capacity_normal |
| 19 |
assert_equal max_embed_len + 1, capa('1' * (max_embed_len + 1)) |
| 20 |
assert_equal max_embed_len + 100, capa('1' * (max_embed_len + 100)) |
| 21 |
end |
| 22 |
|
| 23 |
def test_s_new_capacity |
| 24 |
assert_equal("", String.new(capacity: 1000)) |
| 25 |
assert_equal(String, String.new(capacity: 1000).class) |
| 26 |
assert_equal(10_000, capa(String.new(capacity: 10_000))) |
| 27 |
|
| 28 |
assert_equal("", String.new(capacity: -1000)) |
| 29 |
assert_equal(capa(String.new(capacity: -10000)), capa(String.new(capacity: -1000))) |
| 30 |
end |
| 31 |
|
| 32 |
def test_io_read |
| 33 |
s = String.new(capacity: 1000) |
| 34 |
open(__FILE__) {|f|f.read(1024*1024, s)} |
| 35 |
assert_equal(1024*1024, capa(s)) |
| 36 |
open(__FILE__) {|f|s = f.read(1024*1024)} |
| 37 |
assert_operator(capa(s), :<=, s.bytesize+4096) |
| 38 |
end |
| 39 |
|
| 40 |
def test_literal_capacity |
| 41 |
s = eval(%{ |
| 42 |
# frozen_string_literal: true |
| 43 |
"#{"a" * (max_embed_len + 1)}" |
| 44 |
}) |
| 45 |
assert_equal(s.length, capa(s)) |
| 46 |
end |
| 47 |
|
| 48 |
def test_capacity_frozen |
| 49 |
s = String.new("I am testing", capacity: 1000) |
| 50 |
s << "a" * GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE] |
| 51 |
s.freeze |
| 52 |
assert_equal(s.length, capa(s)) |
| 53 |
end |
| 54 |
|
| 55 |
def test_capacity_fstring |
| 56 |
s = String.new("a" * max_embed_len, capacity: max_embed_len * 3) |
| 57 |
s << "fstring capacity" |
| 58 |
s = -s |
| 59 |
assert_equal(s.length, capa(s)) |
| 60 |
end |
| 61 |
|
| 62 |
private |
| 63 |
|
| 64 |
def capa(str) |
| 65 |
Bug::String.capacity(str) |
| 66 |
end |
| 67 |
|
| 68 |
def embed_header_size |
| 69 |
3 * RbConfig::SIZEOF['void*'] |
| 70 |
end |
| 71 |
|
| 72 |
def max_embed_len |
| 73 |
GC::INTERNAL_CONSTANTS[:RVARGC_MAX_ALLOCATE_SIZE] - embed_header_size - 1 |
| 74 |
end |
| 75 |
end |