File: alignment.rb

package info (click to toggle)
ruby-bindata 2.4.14-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 600 kB
  • sloc: ruby: 8,566; makefile: 4
file content (79 lines) | stat: -rw-r--r-- 1,628 bytes parent folder | download
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
require 'bindata/base_primitive'

module BinData
  # Resets the stream alignment to the next byte.  This is
  # only useful when using bit-based primitives.
  #
  #    class MyRec < BinData::Record
  #      bit4 :a
  #      resume_byte_alignment
  #      bit4 :b
  #    end
  #
  #    MyRec.read("\x12\x34") #=> {"a" => 1, "b" => 3}
  #
  class ResumeByteAlignment < BinData::Base
    def clear?; true; end
    def assign(val); end
    def snapshot; nil; end
    def do_num_bytes; 0; end

    def do_read(io)
      io.reset_read_bits
    end

    def do_write(io)
      io.flushbits
    end
  end

  # A monkey patch to force byte-aligned primitives to
  # become bit-aligned.  This allows them to be used at
  # non byte based boundaries.
  #
  #     class BitString < BinData::String
  #       bit_aligned
  #     end
  #
  #     class MyRecord < BinData::Record
  #       bit4       :preamble
  #       bit_string :str, length: 2
  #     end
  #
  module BitAligned
    class BitAlignedIO
      def initialize(io)
        @io = io
      end
      def readbytes(n)
        n.times.inject("") do |bytes, _|
          bytes += @io.readbits(8, :big).chr
        end
      end
    end

    def bit_aligned?
      true
    end

    def read_and_return_value(io)
      super(BitAlignedIO.new(io))
    end

    def do_num_bytes
      super.to_f
    end

    def do_write(io)
      value_to_binary_string(_value).each_byte { |v| io.writebits(v, 8, :big) }
    end
  end

  def BasePrimitive.bit_aligned
    include BitAligned
  end

  def Primitive.bit_aligned
    fail "'bit_aligned' is not needed for BinData::Primitives"
  end
end