blob: 400c57b437bc057b7f1f49d0f974207a36e07417 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
# -*- frozen-string-literal: true -*-
module Plum
module BinaryString
refine String do
# Reads a 8-bit unsigned integer.
# @param pos [Integer] The start position to read.
def uint8(pos = 0)
getbyte(pos)
end
# Reads a 16-bit unsigned integer.
# @param pos [Integer] The start position to read.
def uint16(pos = 0)
byteslice(pos, 2).unpack("n")[0]
end
# Reads a 24-bit unsigned integer.
# @param pos [Integer] The start position to read.
def uint24(pos = 0)
a, b = byteslice(pos, 3).unpack("nC")
(a * 0x100) + b
end
# Reads a 32-bit unsigned integer.
# @param pos [Integer] The start position to read.
def uint32(pos = 0)
byteslice(pos, 4).unpack("N")[0]
end
# Appends a 8-bit unsigned integer to this string.
def push_uint8(val)
self << val.chr
end
# Appends a 16-bit unsigned integer to this string.
def push_uint16(val)
self << [val].pack("n")
end
# Appends a 24-bit unsigned integer to this string.
def push_uint24(val)
self << [val / 0x100, val % 0x100].pack("nC")
end
# Appends a 32-bit unsigned integer to this string.
def push_uint32(val)
self << [val].pack("N")
end
alias push <<
# Takes from beginning and cut specified *octets* from this String.
# @param count [Integer] The amount.
def byteshift(count)
force_encoding(Encoding::BINARY)
slice!(0, count)
end
def each_byteslice(n, &blk)
if block_given?
pos = 0
while pos < self.bytesize
yield byteslice(pos, n)
pos += n
end
else
Enumerator.new do |y|
each_byteslice(n) {|ss| y << ss }
end
# I want to write `enum_for(__method__, n)`!
end
end
end
end
end
|