Module: Pwnlib::Util::Lists

Included in:
Pwn, Shellcraft::Generators::Helper::Runner
Defined in:
lib/pwnlib/util/lists.rb

Overview

Methods related to group / slice string into lists.

Class Method Summary collapse

Class Method Details

.slice(n, str, underfull_action: :ignore, fill_value: nil) ⇒ Array<String> Also known as: group

Split sequence into subsequences of given size. If the values cannot be evenly distributed among into groups, then the last group will either be dropped or padded with the value specified in fill_value.

Examples:

slice(2, 'ABCDE') #=> ['AB', 'CD', 'E']
slice(2, 'ABCDE', underfull_action: :fill, fill_value: 'X')
=> ['AB', 'CD', 'EX']
slice(2, 'ABCDE', underfull_action: :drop)
=> ['AB', 'CD']

Parameters:

  • n (Integer)

    The desired size of each subsequences.

  • str (String)

    The sequence to be grouped.

  • underfull_action (:ignore, :drop, :fill) (defaults to: :ignore)

    Action to take when size of str is not a mulitple of n.

  • fill_value (String) (defaults to: nil)

    The padding byte. Only meaningful when str cannot be grouped equally and underfull_action == :fill.

Returns:

  • (Array<String>)

    The split result.

Difference with Python pwntools:

  • This method named group in python-pwntools, but this is more similar to Array#each_slice in ruby.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pwnlib/util/lists.rb', line 37

def slice(n, str, underfull_action: :ignore, fill_value: nil)
  unless %i(ignore drop fill).include?(underfull_action)
    raise ArgumentError, 'underfull_action expect to be one of :ignore, :drop, and :fill'
  end

  sliced = str.chars.each_slice(n).map(&:join)
  case underfull_action
  when :drop
    sliced.pop unless sliced.last.size == n
  when :fill
    remain = n - sliced.last.size
    fill_value = fill_value.to_s
    raise ArgumentError, 'fill_value must be a character' unless fill_value.size == 1

    sliced.last.concat(fill_value * remain)
  end
  sliced
end