Class: XDR::String

Inherits:
Object
  • Object
show all
Includes:
Concerns::ConvertsToXDR, Concerns::StringConverter
Defined in:
lib/xdr/string.rb

Instance Method Summary collapse

Methods included from Concerns::StringConverter

#valid?

Methods included from Concerns::ConvertsToXDR

#from_xdr, #to_xdr, #valid?

Constructor Details

#initialize(length = XDR::MAX_SIZE) ⇒ String

Returns a new instance of String.



7
8
9
# File 'lib/xdr/string.rb', line 7

def initialize(length = XDR::MAX_SIZE)
  @length = length
end

Instance Method Details

#read(io) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/xdr/string.rb', line 23

def read(io)
  length = XDR::Int.read(io)

  if length > @length
    raise XDR::ReadError, "String length #{length} is greater than max"
  end

  padding = padding_for length

  # read and return length bytes
  # throw away padding bytes
  read_bytes(io, length).tap { read_zeros(io, padding) }
end

#write(val, io) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/xdr/string.rb', line 11

def write(val, io)
  length = val.bytesize

  if length > @length
    raise XDR::WriteError, "Value length #{length} exceeds max #{@length}"
  end

  XDR::Int.write(length, io)
  io.write val
  io.write "\x00" * padding_for(length)
end