forked from cloudfoundry/cloud_controller_ng
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyte_converter.rb
More file actions
41 lines (32 loc) · 1.28 KB
/
byte_converter.rb
File metadata and controls
41 lines (32 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
require 'cloud_controller/byte_quantity'
module VCAP::CloudController
class ByteConverter
class InvalidBytesError < StandardError; end
class InvalidUnitsError < StandardError; end
class NonNumericError < StandardError; end
def convert_to_mb(human_readable_byte_value)
return nil if human_readable_byte_value.blank?
raise NonNumericError unless human_readable_byte_value.to_s.match?(/\A-?\d+(?:\.\d+)?/)
ByteQuantity.to_megabytes(human_readable_byte_value.to_s)
rescue ByteQuantity::InvalidByteQuantityError
raise InvalidUnitsError
end
def convert_to_b(human_readable_byte_value)
return nil if human_readable_byte_value.blank?
raise NonNumericError unless human_readable_byte_value.to_s.match?(/\A-?\d+(?:\.\d+)?/)
ByteQuantity.to_bytes(human_readable_byte_value.to_s)
rescue ByteQuantity::InvalidByteQuantityError
raise InvalidUnitsError
end
def human_readable_byte_value(bytes)
return nil if bytes.blank?
raise InvalidBytesError unless bytes.is_a?(Integer)
units = %w[B K M G T]
while units.any?
unit_in_bytes = 1024**(units.length - 1)
return "#{bytes / unit_in_bytes}#{units.last}" if bytes.remainder(unit_in_bytes).zero?
units.pop
end
end
end
end