Module: PyBind::Operator

Included in:
PyObjectWrapper
Defined in:
lib/pybind/wrapper/operator.rb

Constant Summary collapse

BINARY_OPERATION_OPFUNCS =
{
  :+ => :PyNumber_Add,
  :- => :PyNumber_Subtract,
  :* => :PyNumber_Multiply,
  :/ => :PyNumber_TrueDivide,
  :% => :PyNumber_Remainder,
  :<< => :PyNumber_Lshift,
  :>> => :PyNumber_Rshift,
  :& => :PyNumber_And,
  :^ => :PyNumber_Xor,
  :| => :PyNumber_Or
}.freeze
UNARY_OPERATION_OPFUNCS =
{
  :+@ => :PyNumber_Positive,
  :-@ => :PyNumber_Negative,
  :~ => :PyNumber_Invert,
}.freeze

Instance Method Summary collapse

Instance Method Details

#!Object



76
77
78
79
80
# File 'lib/pybind/wrapper/operator.rb', line 76

def !
  value = LibPython.PyObject_Not(@pystruct)
  raise PyError.fetch if value == -1
  value == 1
end

#**(other) ⇒ Object



53
54
55
56
57
58
# File 'lib/pybind/wrapper/operator.rb', line 53

def **(other)
  other = other.to_python
  value = LibPython.PyNumber_Power(@pystruct, other, PyBind.None)
  raise PyError.fetch if value.null?
  value.to_ruby
end

#<=>(other) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/pybind/wrapper/operator.rb', line 60

def <=>(other)
  if LibPython.respond_to? :PyObject_Compare
    other = other.to_python
    value = LibPython.PyObject_Compare(@pystruct, other)
    raise PyError.fetch unless LibPython.PyErr_Occurred().null?
    value
  else
    (self > other) - (self < other)
  end
end

#===(other) ⇒ Object



71
72
73
74
# File 'lib/pybind/wrapper/operator.rb', line 71

def ===(other)
  other = other.to_python
  @pystruct.to_ptr == other.to_ptr
end

#__binary_operate__(other, op) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
# File 'lib/pybind/wrapper/operator.rb', line 22

def __binary_operate__(other, op)
  opfunc = BINARY_OPERATION_OPFUNCS[op]
  raise ArgumentError, "Unknown binary operation op: #{op}" unless opfunc

  other = other.to_python
  value = LibPython.send(opfunc, @pystruct, other)
  raise PyError.fetch if value.null?
  value.to_ruby
end

#__unary_operate__(op) ⇒ Object

Raises:

  • (ArgumentError)


38
39
40
41
42
43
44
45
# File 'lib/pybind/wrapper/operator.rb', line 38

def __unary_operate__(op)
  opfunc = UNARY_OPERATION_OPFUNCS[op]
  raise ArgumentError, "Unknown unary operation op: #{op}" unless opfunc

  value = LibPython.send(opfunc, @pystruct)
  raise PyError.fetch if value.null?
  value.to_ruby
end