Class: Nl::Decoder

Inherits:
Object
  • Object
show all
Defined in:
lib/nl/decoder.rb

Defined Under Namespace

Classes: Error, OutOfBounds, Unterminated

Instance Method Summary collapse

Constructor Details

#initialize(buffer, offset = 0, length = buffer.size - offset) ⇒ Decoder

Returns a new instance of Decoder.



11
12
13
14
15
# File 'lib/nl/decoder.rb', line 11

def initialize(buffer, offset = 0, length = buffer.size - offset)
  @buffer = buffer
  @position = offset
  @limit = length
end

Instance Method Details

#align_to(alignment) ⇒ Object

Raises:



80
81
82
83
84
# File 'lib/nl/decoder.rb', line 80

def align_to(alignment)
  nposition = (@position + alignment - 1) & ~(alignment - 1)
  raise OutOfBounds if nposition > @limit
  @position = nposition
end

#available?(size = 1) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/nl/decoder.rb', line 17

def available?(size = 1)
  @position + size <= @limit
end

#get_string(length = @limit - @position) ⇒ Object

Raises:



39
40
41
42
43
44
45
# File 'lib/nl/decoder.rb', line 39

def get_string(length = @limit - @position)
  nposition = @position + length
  raise OutOfBounds if nposition > @limit
  value = @buffer.get_string(@position, length)
  @position = nposition
  value
end

#get_value(type) ⇒ Object

Raises:



64
65
66
67
68
69
70
# File 'lib/nl/decoder.rb', line 64

def get_value(type)
  nposition = @position + IO::Buffer.size_of(type)
  raise OutOfBounds if nposition > @limit
  value = @buffer.get_value(type, @position)
  @position = nposition
  value
end

#get_values(types) ⇒ Object

Raises:



72
73
74
75
76
77
78
# File 'lib/nl/decoder.rb', line 72

def get_values(types)
  nposition = @position + IO::Buffer.size_of(types)
  raise OutOfBounds if nposition > @limit
  values = @buffer.get_values(types, @position)
  @position = nposition
  values
end

#get_zstring(unterminated_ok: false) ⇒ Object

Raises:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/nl/decoder.rb', line 47

def get_zstring(unterminated_ok: false)
  nposition = @position
  nul_found = false
  while nposition < @limit
    c = @buffer.get_value(:U8, nposition)
    nposition += 1
    if c == 0
      nul_found = true
      break
    end
  end
  raise Unterminated if !nul_found && !unterminated_ok
  value = @buffer.get_string(@position, nposition - @position - (nul_found ? 1 : 0))
  @position = nposition
  value
end

#limit(size) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nl/decoder.rb', line 21

def limit(size)
  orig_limit = @limit
  @limit = @position + size
  result = yield self
  if @limit != @position
    raise "Not all bytes upto specified limit is consumed"
  end
  result
ensure
  @limit = orig_limit
end

#skip(length = @limit - @position) ⇒ Object

Raises:



33
34
35
36
37
# File 'lib/nl/decoder.rb', line 33

def skip(length = @limit - @position)
  nposition = @position + length
  raise OutOfBounds if nposition > @limit
  @position = nposition
end