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


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类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。