class TTY::Command::Truncator

Retains the first N bytes and the last N bytes from written content

@api private

Constants

DEFAULT_SIZE

Default maximum byte size for prefix & suffix

Public Class Methods

new(options = {}) click to toggle source

Create a Truncator

@param [Hash] options @option options [Number] max_size

@api public

# File lib/tty/command/truncator.rb, line 18
def initialize(options = {})
  @max_size = options.fetch(:max_size) { DEFAULT_SIZE }
  @prefix   = ""
  @suffix   = ""
  @skipped  = 0
end

Public Instance Methods

<<(content)
Alias for: write
read() click to toggle source

Truncated representation of the content

@return [String]

@api public

# File lib/tty/command/truncator.rb, line 57
def read
  return @prefix if @suffix.empty?

  if @skipped.zero?
    return @prefix << @suffix
  end

  @prefix + "\n... omitting #{@skipped} bytes ...\n" + @suffix
end
Also aliased as: to_s
to_s()
Alias for: read
write(content) click to toggle source

Write content

@param [String] content

the content to write

@return [nil]

@api public

# File lib/tty/command/truncator.rb, line 33
def write(content)
  content = content.to_s.dup

  content, @prefix = append(content, @prefix)

  if (over = (content.bytesize - @max_size)) > 0
    content = content.byteslice(over..-1)
    @skipped += over
  end

  content, @suffix = append(content, @suffix)

  # suffix is full but we still have content to write
  while content.bytesize > 0
    content = copy(content, @suffix)
  end
end
Also aliased as: <<

Private Instance Methods

append(value, dst) click to toggle source

Append value to destination

@param [String] value

@param [String] dst

@api private

# File lib/tty/command/truncator.rb, line 93
def append(value, dst)
  remain    = @max_size - dst.bytesize
  remaining = ""
  if remain > 0
    value_bytes = value.to_s.bytesize
    offset = value_bytes < remain ? value_bytes : remain
    remaining = value.byteslice(0...offset)
    value = value.byteslice(offset..-1)
  end
  [value, dst + remaining]
end
copy(value, dest) click to toggle source

Copy minimum bytes from source to destination

@return [String]

the remaining content

@api private

# File lib/tty/command/truncator.rb, line 76
def copy(value, dest)
  bytes = value.bytesize
  n = bytes < dest.bytesize ? bytes : dest.bytesize

  head, tail = dest.byteslice(0...n), dest.byteslice(n..-1)
  dest.replace("#{tail}#{value[0...n]}")
  @skipped += head.bytesize
  value.byteslice(n..-1)
end