Class: Netstring

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/netstring.rb

Overview

A netstring parser and emitter.

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n, start, length) ⇒ Netstring

Initializes a netstring.

The netstring may be multiple concatenated netstrings.

Parameters:

  • n (String)

    a netstring

  • start (Integer)

    the start of the string in the netstring

  • length (Integer)

    the length of the string in the netstring



56
57
58
59
60
# File 'lib/netstring.rb', line 56

def initialize(n, start, length)
  super(n[start, length])

  @netstring = n[0, start + length + 1]
end

Instance Attribute Details

#netstringString (readonly)

Returns the netstring.

Returns:

  • (String)

    the netstring



12
13
14
# File 'lib/netstring.rb', line 12

def netstring
  @netstring
end

Class Method Details

.dump(s) ⇒ String

Dumps a string to a netstring.

Parameters:

  • s (String)

    a string

Returns:

  • (String)

    a netstring



18
19
20
21
22
23
# File 'lib/netstring.rb', line 18

def self.dump(s)
  unless String === s
    raise Error, "#{s.inspect} is not a String"
  end
  "#{s.size}:#{s},"
end

.load(n) ⇒ Netstring

Loads a string from a netstring.

The netstring may be multiple concatenated netstrings.

The return value is a Netstring object, whose #to_s method returns the string, and whose #offset method returns the length of the netstring.

Parameters:

  • n (String)

    a netstring

Returns:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/netstring.rb', line 34

def self.load(n)
  unless String === n
    raise Error, "#{n.inspect} is not a String"
  end
  match = n.match(/\A(\d+):/)
  unless match
    raise Error, 'bad netstring header'
  end
  size = Integer(match[1])
  unless n[match.end(0) + size] == ','
    raise Error, 'expected "," delimiter'
  end
  Netstring.new(n, match.end(0), size)
end