Class: Rbkb::Cli::Len

Inherits:
Executable show all
Defined in:
lib/rbkb/cli/len.rb

Overview

len prepends a binary length number in front of its input and outputs raw on STDOUT

Instance Attribute Summary

Attributes inherited from Executable

#argv, #exit_status, #oparse, #opts, #stderr, #stdin, #stdout

Instance Method Summary collapse

Methods inherited from Executable

#bail, #bail_args, #exit, run

Constructor Details

#initialize(*args) ⇒ Len

Returns a new instance of Len.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rbkb/cli/len.rb', line 9

def initialize(*args)
  # endianness pair. index 0 is always the default
  @endpair = %i[big little]

  super(*args) do |this|
    {
      nudge: 0,
      size: 4,
      endian: @endpair[0]
    }.each { |k, v| this.opts[k] ||= v }

    yield this if block_given?
  end
end

Instance Method Details

#go(*args) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/rbkb/cli/len.rb', line 58

def go(*args)
  super(*args)
  unless len = @opts[:static]
    len = @opts[:indat].size
    len += @opts[:size] if @opts[:tot]
    len += @opts[:nudge]
  end
  @stdout << len.to_bytes(@opts[:endian], @opts[:size]) << @opts[:indat]
  self.exit(0)
end

#make_parser ⇒ Object



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
# File 'lib/rbkb/cli/len.rb', line 24

def make_parser
  super()
  add_std_file_opt(:indat)
  arg = @oparse
  arg.banner += ' <data | blank for stdin>'

  arg.on('-n', '--nudge INT', Numeric, 'Add integer to length') do |n|
    @opts[:nudge] += n
  end

  arg.on('-s', '--size=SIZE', Numeric, 'Size of length field in bytes') do |s|
    bail('Size must be greater than 0') unless (@opts[:size] = s) > 0
  end

  arg.on('-x', '--[no-]swap', "Swap endianness. Default=#{@opts[:endian]}") do |x|
    @opts[:endian] = @endpair[x ? 1 : 0]
  end

  arg.on('-t', '--[no-]total', 'Include size word in size') do |t|
    @opts[:tot] = t
  end

  arg.on('-l', '--length=LEN', Numeric, 'Ignore all other flags and use static LEN') do |l|
    @opts[:static] = l
  end
end

#parse(*args) ⇒ Object



51
52
53
54
55
56
# File 'lib/rbkb/cli/len.rb', line 51

def parse(*args)
  super(*args)
  @opts[:indat] ||= @argv.shift
  parse_catchall
  @opts[:indat] ||= @stdin.read
end