Crystal:如何互相复制String::Builder
Crystal: how to copy String::Builder s to each other
我想将一个 String::Builder 上的内容写入另一个,例如:
str1 = String::Builder.new
str2 = String::Builder.new
str1 << "foo"
str2 << "bar"
str1.copy_somehow_another_builder(str2) #=> "foobar"
目前我只是str1 << str2.to_s
。
怎么做?
从性能的角度来看,to_s'ing 和 push 是否与我想要的相同?
如果有人遇到问题,您可以使用 IO::Memory 达到同样的目的,例如:
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"
我想将一个 String::Builder 上的内容写入另一个,例如:
str1 = String::Builder.new
str2 = String::Builder.new
str1 << "foo"
str2 << "bar"
str1.copy_somehow_another_builder(str2) #=> "foobar"
目前我只是str1 << str2.to_s
。
怎么做? 从性能的角度来看,to_s'ing 和 push 是否与我想要的相同?
如果有人遇到问题,您可以使用 IO::Memory 达到同样的目的,例如:
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"