Class: Pocolog::Upgrade::Ops::NumericCast
- Defined in:
- lib/pocolog/upgrade/ops/numeric_cast.rb
Instance Attribute Summary collapse
-
#range_max ⇒ Numeric?
readonly
Maximum value allowed in Base#to_type if a range check is needed.
-
#range_min ⇒ Numeric?
readonly
Minimum value allowed in Base#to_type if a range check is needed.
Attributes inherited from Base
Instance Method Summary collapse
-
#compute_integer_range(type) ⇒ Object
private
Compute the range for the given type.
- #convert(value) ⇒ Object
-
#initialize(from_t, to_t) ⇒ NumericCast
constructor
A new instance of NumericCast.
Methods inherited from Base
Constructor Details
#initialize(from_t, to_t) ⇒ NumericCast
Returns a new instance of NumericCast
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/pocolog/upgrade/ops/numeric_cast.rb', line 17 def initialize(from_t, to_t) super(to_t) if from_t.integer? from_range = compute_integer_range(from_t) end if to_t.integer? to_range = compute_integer_range(to_t) end if !from_range if to_range @range_min, @range_max = *to_range end elsif to_range && (from_range.first < to_range.first || from_range.last > to_range.last) @range_min, @range_max = *to_range end end |
Instance Attribute Details
#range_max ⇒ Numeric? (readonly)
Maximum value allowed in Base#to_type if a range check is needed
15 16 17 |
# File 'lib/pocolog/upgrade/ops/numeric_cast.rb', line 15 def range_max @range_max end |
#range_min ⇒ Numeric? (readonly)
Minimum value allowed in Base#to_type if a range check is needed
9 10 11 |
# File 'lib/pocolog/upgrade/ops/numeric_cast.rb', line 9 def range_min @range_min end |
Instance Method Details
#compute_integer_range(type) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Compute the range for the given type
37 38 39 40 41 42 43 44 |
# File 'lib/pocolog/upgrade/ops/numeric_cast.rb', line 37 def compute_integer_range(type) if type.unsigned? [0, 2**type.size] else limit = 2**(type.size - 1) [-(limit-1), limit] end end |
#convert(value) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/pocolog/upgrade/ops/numeric_cast.rb', line 46 def convert(value) ruby_value = Typelib.to_ruby(value) if range_min if ruby_value < range_min raise RangeError, "value below minimum value for #{to_type}" elsif ruby_value > range_max raise RangeError, "value above maximum value for #{to_type}" end end Typelib.from_ruby(ruby_value, to_type) end |