aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/binary_string.rb
blob: 02b417b108b4862ad04f29b5c0c4ed8b9d09b29f (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# 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

      # Splits this String into chunks.
      # @param n [Integer] max chunk bytesize
      # @return [Array<String>] the slices
      def chunk(n)
        res = []
        pos = 0
        lim = bytesize
        while pos < lim
          res << byteslice(pos, n)
          pos += n
        end
        res
      end
    end
  end
end