aboutsummaryrefslogtreecommitdiffstats
path: root/lib/plum/binary_string.rb
blob: 72b38b10f4ce7b8e40ba9d3c189fd5593b5210aa (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
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)
        byteslice(pos, 1).unpack("C")[0]
      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)
        (uint16(pos) << 8) | uint8(pos + 2)
      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].pack("C")
      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)
        push_uint16(val >> 8)
        push_uint8(val & ((1 << 8) - 1))
      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