当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Buffer.copy用法及代码示例


本文简要介绍ruby语言中 IO::Buffer.copy 的用法。

用法

copy(source, [offset, [length, [source_offset]]]) → size

使用 memcpy 有效地将数据从源 IO::Buffer 复制到缓冲区 offset 中。要复制 String 实例,请参阅 set_string

buffer = IO::Buffer.new(32)
#  =>
# #<IO::Buffer 0x0000555f5ca22520+32 INTERNAL>
# 0x00000000  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
# 0x00000010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................  *

buffer.copy(IO::Buffer.for("test"), 8)
# => 4 -- size of data copied
buffer
#  =>
# #<IO::Buffer 0x0000555f5cf8fe40+32 INTERNAL>
# 0x00000000  00 00 00 00 00 00 00 00 74 65 73 74 00 00 00 00 ........test....
# 0x00000010  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ *

copy 可用于将数据放入与缓冲区关联的字符串中:

string= "data:    "
# => "data:    "
buffer = IO::Buffer.for(str)
buffer.copy(IO::Buffer.for("test"), 5)
# => 4
string
# => "data:test"

尝试复制到只读缓冲区将失败:

File.write('test.txt', 'test')
buffer = IO::Buffer.map(File.open('test.txt'), nil, 0, IO::Buffer::READONLY)
buffer.copy(IO::Buffer.for("test"), 8)
# in `copy': Buffer is not writable! (IO::Buffer::AccessError)

有关创建可变文件映射的详细信息,请参阅 ::map ,这将起作用:

buffer = IO::Buffer.map(File.open('test.txt', 'r+'))
buffer.copy("boom", 0)
# => 4
File.read('test.txt')
# => "boom"

尝试复制需要放置在缓冲区边界之外的数据将失败:

buffer = IO::Buffer.new(2)
buffer.copy('test', 0)
# in `copy': Specified offset+length exceeds source size! (ArgumentError)

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Buffer.copy。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。