Skip to content
Permalink
Browse files
Optimize String::Builder#write_byte
  • Loading branch information
asterite committed Aug 19, 2017
1 parent 6278e34 commit 1655935
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
@@ -2163,6 +2163,17 @@ describe "String" do
"fo\u{0000}".compare("FO", case_insensitive: true).should eq(1)
end

it "builds with write_byte" do
string = String.build do |io|
255_u8.times do |byte|
io.write_byte(byte)
end
end
255.times do |i|
string.byte_at(i).should eq(i)
end
end

it "raises if String.build negative capacity" do
expect_raises(ArgumentError, "Negative capacity") do
String.build(-1) { }
@@ -53,6 +53,19 @@ class String::Builder
nil
end

def write_byte(byte : UInt8)
new_bytesize = real_bytesize + 1
if new_bytesize > @capacity
resize_to_capacity(Math.pw2ceil(new_bytesize))
end

@buffer[real_bytesize] = byte

@bytesize += 1

nil
end

def buffer
@buffer + String::HEADER_SIZE
end

0 comments on commit 1655935

Please sign in to comment.