Skip to content

Commit

Permalink
Optimize String::Builder#write_byte
Browse files Browse the repository at this point in the history
  • 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.
11 changes: 11 additions & 0 deletions spec/std/string_spec.cr
Expand Up @@ -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) { }
Expand Down
13 changes: 13 additions & 0 deletions src/string/builder.cr
Expand Up @@ -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
Expand Down

0 comments on commit 1655935

Please sign in to comment.