Module: Aspera::Units::Decimal

Defined in:
lib/aspera/units/decimal.rb

Overview

Rates and sizes in decimal units (prefixes K, M, G... x1000, like ascp): parsed from user input and formatted for display. Depends only on aspera/assert: usable without the CLI.

Constant Summary collapse

PREFIX =

Decimal prefixes: each one is KILO times the previous one

['', 'K', 'M', 'G', 'T', 'P'].freeze
KILO =
1000

Class Method Summary collapse

Class Method Details

.format_bytes(bytes) ⇒ String

Returns Size with decimal unit, e.g. 12.3 MB.

Parameters:

  • bytes (Integer) —

    Size in bytes

Returns:

  • (String) —

    Size with decimal unit, e.g. 12.3 MB



46
47
48
49
50
51
52
53
54
55
# File 'lib/aspera/units/decimal.rb', line 46

def format_bytes(bytes)
  value = bytes.to_f
  index = 0
  while value >= KILO && index < BYTE_UNITS.length - 1
    value /= KILO
    index += 1
  end
  return "#{bytes} B" if index.zero?
  format('%.1f %s', value, BYTE_UNITS[index])
end

.format_rate(bytes_per_second) ⇒ String

Returns Rate in megabits per second (decimal, like ascp).

Parameters:

  • bytes_per_second (Float, nil) —

    Rate, nil if unknown

Returns:

  • (String) —

    Rate in megabits per second (decimal, like ascp)



59
60
61
62
63
# File 'lib/aspera/units/decimal.rb', line 59

def format_rate(bytes_per_second)
  return '-- Mbps' if bytes_per_second.nil?
  mbps = bytes_per_second * BITS_PER_BYTE / MULTIPLIER.fetch('M')
  mbps < 10 ? format('%.2f Mbps', mbps) : format('%.0f Mbps', mbps)
end

.rate_bps_to_string(bps) ⇒ String

Inverse of rate_string_to_bps: the shortest exact text, e.g. 100M, 1G, 1500K, 999

Parameters:

  • bps (Integer) —

    Rate in bits per second

Returns:

  • (String) —

    Rate accepted by rate_string_to_bps



39
40
41
42
# File 'lib/aspera/units/decimal.rb', line 39

def rate_bps_to_string(bps)
  prefix = PREFIX.reverse.find { |candidate| bps.positive? && (bps % MULTIPLIER[candidate]).zero? } || ''
  "#{bps / MULTIPLIER[prefix]}#{prefix}"
end

.rate_string_to_bps(value) ⇒ Integer

Parse a human-readable rate (as accepted by async -l) into an integer bps value. Accepted: plain integer (bps), or integer + prefix of PREFIX, case ignored, e.g. k (x1000), M (x1000000), g (x1000000000).

Parameters:

  • value (String, Integer) —

    e.g. "100m", "500000", "1g", 500000

Returns:

  • (Integer) —

    value in bps



30
31
32
33
34
# File 'lib/aspera/units/decimal.rb', line 30

def rate_string_to_bps(value)
  m = RATE_INPUT.match(value.to_s.strip)
  Aspera.assert(m, type: ParameterError) { "Invalid rate value: #{value.inspect}. Expected integer with optional suffix #{PREFIX.drop(1).join(', ')} (case ignored)." }
  return m[1].to_i * MULTIPLIER.fetch(m[2].to_s.upcase)
end