From e7144af7504aca614b8f9e04aba848afd3e70945 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Sun, 29 Sep 2024 19:07:16 +0900 Subject: [PATCH] [DOC] Refine about offset directives --- doc/packed_data.rdoc | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/doc/packed_data.rdoc b/doc/packed_data.rdoc index 17bbf92023..fa95db9106 100644 --- a/doc/packed_data.rdoc +++ b/doc/packed_data.rdoc @@ -564,26 +564,42 @@ for one byte in the input or output string. == Offset Directives - '@' - Begin packing at the given byte offset; - for packing, null fill if necessary: + for packing, null fill or shrink if necessary: - [1, 2].pack("C@0C") # => "\x02" - [1, 2].pack("C@1C") # => "\x01\x02" - [1, 2].pack("C@5C") # => "\x01\x00\x00\x00\x00\x02" + [1, 2].pack("C@0C") # => "\x02" + [1, 2].pack("C@1C") # => "\x01\x02" + [1, 2].pack("C@5C") # => "\x01\x00\x00\x00\x00\x02" + [*1..5].pack("CCCC@2C") # => "\x01\x02\x05" + + For unpacking, cannot to move to outside the string: "\x01\x00\x00\x02".unpack("C@3C") # => [1, 2] "\x00".unpack("@1C") # => [nil] + "\x00".unpack("@2C") # Raises ArgumentError. -- 'X' - Back up a byte: +- 'X' - For packing, shrink for the given byte offset: [0, 1, 2].pack("CCXC") # => "\x00\x02" [0, 1, 2].pack("CCX2C") # => "\x02" + + For unpacking; rewind unpacking position for the given byte offset: + "\x00\x02".unpack("CCXC") # => [0, 2, 2] -== Null Byte Directive + Cannot to move to outside the string: -- 'x' - Null byte: + [0, 1, 2].pack("CCX3C") # Raises ArgumentError. + "\x00\x02".unpack("CX3C") # Raises ArgumentError. + +- 'x' - Begin packing at after the given byte offset; + for packing, null fill if necessary: [].pack("x0") # => "" [].pack("x") # => "\x00" [].pack("x8") # => "\x00\x00\x00\x00\x00\x00\x00\x00" + + For unpacking, cannot to move to outside the string: + "\x00\x00\x02".unpack("CxC") # => [0, 2] + "\x00\x00\x02".unpack("x3C") # => [nil] + "\x00\x00\x02".unpack("x4C") # Raises ArgumentError