當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。