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


Ruby Buffer類用法及代碼示例


本文簡要介紹ruby語言中 IO::Buffer類 的用法。

IO::Buffer 是用於輸入/輸出的低級高效緩衝區。緩衝區的三種使用方式:

與字符串和文件內存的交互由高效的低級 C 機製(如“memcpy”)執行。

該類旨在成為實現更高級機製的實用程序,例如 Fiber::SchedulerInterface#io_read Fiber::SchedulerInterface#io_write

使用示例:

空緩衝區:

buffer = IO::Buffer.new(8)  # create empty 8-byte buffer
#  =>
# #<IO::Buffer 0x0000555f5d1a5c50+8 INTERNAL>
# ...
buffer
#  =>
# <IO::Buffer 0x0000555f5d156ab0+8 INTERNAL>
# 0x00000000  00 00 00 00 00 00 00 00
buffer.set_string('test', 2) # put there bytes of the "test" string, starting from offset 2
# => 4
buffer.get_string  # get the result
# => "\x00\x00test\x00\x00"

來自字符串的緩衝區:

string = 'data'
buffer = IO::Buffer.for(str)
#  =>
# #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
# ...
buffer
#  =>
# #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
# 0x00000000  64 61 74 61                                     data

buffer.get_string(2)  # read content starting from offset 2
# => "ta"
buffer.set_string('---', 1) # write content, starting from offset 1
# => 3
buffer
#  =>
# #<IO::Buffer 0x00007f3f02be9b18+4 SLICE>
# 0x00000000  64 2d 2d 2d                                     d---
string  # original string changed, too
# => "d---"

來自文件的緩衝區:

File.write('test.txt', 'test data')
# => 9
buffer = IO::Buffer.map(File.open('test.txt'))
#  =>
# #<IO::Buffer 0x00007f3f0768c000+9 MAPPED IMMUTABLE>
# ...
buffer.get_string(5, 2) # read 2 bytes, starting from offset 5
# => "da"
buffer.set_string('---', 1) # attempt to write
# in `set_string': Buffer is not writable! (IO::Buffer::AccessError)

# To create writable file-mapped buffer
# Open file for read-write, pass size, offset, and flags=0
buffer = IO::Buffer.map(File.open('test.txt', 'r+'), 9, 0, 0)
buffer.set_string('---', 1)
# => 3 -- bytes written
File.read('test.txt')
# => "t--- data"

該課程是實驗性的,接口可能會發生變化。

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Buffer類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。