Search code examples
crystal-lang

Crystal: how to copy String::Builder s to each other


I want to write contents on one String::Builder to another, like:

str1 = String::Builder.new
str2 = String::Builder.new

str1 << "foo"
str2 << "bar"

str1.copy_somehow_another_builder(str2) #=> "foobar"

currently I just str1 << str2.to_s.

How to do it? And is to_s'ing and pushing is same as what I want from performance point of view?


Solution

  • If any one meets with the problem, you can use IO::Memory for the same purpose like:

    io = IO::Memory.new 128
    io2 = IO::Memory.new 128
    
    io << "foo"
    io2 << "bar"
    
    buffer = uninitialized UInt8[128]
    
    io2.rewind
    
    if (read_bytes_length = io2.read(buffer.to_slice)) > 0
      io.write( buffer.to_slice[0, read_bytes_length] )
    end
    
    p io.to_s #=> "foobar"