Class: CF::Number

Inherits:
Base
  • Object
show all
Includes:
Comparable
Defined in:
lib/corefoundation/number.rb

Overview

Wrapper for CFNumberRef

Instance Attribute Summary

Attributes inherited from Base

#ptr

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

check_cftype, #eql?, #equals?, finalize, #hash, #initialize, #null?, #to_cf, typecast

Methods included from Memory

#inspect, #release, #retain, #to_ptr

Methods included from Register

included, #register_type

Constructor Details

This class inherits a constructor from CF::Base

Class Method Details

.from_f(float) ⇒ CF::Number

Constructs a CF::Number from a float

Parameters:

  • float (Float)

Returns:



39
40
41
42
43
# File 'lib/corefoundation/number.rb', line 39

def self.from_f(float)
  p = FFI::MemoryPointer.new(:double)
  p.write_double(float.to_f)
  new(CF.CFNumberCreate(nil, :kCFNumberDoubleType, p))
end

.from_i(int) ⇒ CF::Number

Constructs a CF::Number from an integer

Parameters:

  • int (Integer)

Returns:



48
49
50
51
52
# File 'lib/corefoundation/number.rb', line 48

def self.from_i(int)
  p = FFI::MemoryPointer.new(:int64)
  p.put_int64(0,int.to_i)
  new(CF.CFNumberCreate(nil, :kCFNumberSInt64Type, p))
end

Instance Method Details

#<=>(other) ⇒ Integer

Compares the receiver with the argument

Parameters:

Returns:

  • (Integer)

Raises:

  • (TypeError)


57
58
59
60
# File 'lib/corefoundation/number.rb', line 57

def <=>(other)
  raise TypeError, "argument should be CF::Number" unless other.is_a?(CF::Number)
  CF.CFNumberCompare(self,other,nil)
end

#to_fFloat

Converts the CF::Number to a float May raise if the conversion cannot be done without loss of precision

Returns:

  • (Float)


89
90
91
92
93
94
95
96
# File 'lib/corefoundation/number.rb', line 89

def to_f
  p = FFI::MemoryPointer.new(:double)
  if CF.CFNumberGetValue(self, :kCFNumberDoubleType, p) != 0
    p.read_double
  else
    raise "CF.CFNumberGetValue failed to convert #{self.inspect} to kCFNumberDoubleType"
  end
end

#to_iInteger

Converts the CF::Number to an integer May raise if the conversion cannot be done without loss of precision

Returns:

  • (Integer)


77
78
79
80
81
82
83
84
# File 'lib/corefoundation/number.rb', line 77

def to_i
  p = FFI::MemoryPointer.new(:int64)
  if CF.CFNumberGetValue(self, :kCFNumberSInt64Type, p) != 0
    p.get_int64 0
  else
    raise "CF.CFNumberGetValue failed to convert #{self.inspect} to kCFNumberSInt64Type"
  end
end

#to_rubyInteger, Float

Converts the CF::Number to either an Integer or a Float, depending on the result of CFNumberIsFloatType

Returns:

  • (Integer, Float)


66
67
68
69
70
71
72
# File 'lib/corefoundation/number.rb', line 66

def to_ruby
  if CF.CFNumberIsFloatType(self) == 0
    to_i
  else
    to_f
  end
end