Permalink
Browse files

Add Complex type

This is a representation of the Python complex type.
  • Loading branch information...
1 parent 1e9ded6 commit 79166a65c2ea5bfd32072ee12342578cea12a311 @qur committed Aug 24, 2011
Showing with 55 additions and 0 deletions.
  1. +1 −0 lib/Makefile
  2. +51 −0 lib/complex.go
  3. +2 −0 lib/object.go
  4. +1 −0 lib/utils.c
View
@@ -19,6 +19,7 @@ CGOFILES=\
class_sequence.go \
class_standard.go \
code.go \
+ complex.go \
dict.go \
err.go \
eval.go \
View
@@ -0,0 +1,51 @@
+// Copyright 2011 Julian Phillips. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package py
+
+// #include "utils.h"
+// static inline int complexCheck(PyObject *o) { return PyComplex_Check(o); }
+import "C"
+
+import (
+ "fmt"
+ "os"
+ "unsafe"
+)
+
+type Complex struct {
+ AbstractObject
+ o C.PyComplexObject
+}
+
+var ComplexType = (*Type)(unsafe.Pointer(&C.PyComplex_Type))
+
+func complexCheck(obj Object) bool {
+ return C.complexCheck(c(obj)) != 0
+}
+
+func newComplex(obj *C.PyObject) *Complex {
+ return (*Complex)(unsafe.Pointer(obj))
+}
+
+func NewComplex(v complex128) (*Complex, os.Error) {
+ ret := C.PyComplex_FromDoubles(C.double(real(v)), C.double(imag(v)))
+ if ret == nil {
+ return nil, exception()
+ }
+ return newComplex(ret), nil
+}
+
+func (o *Complex) Complex128() complex128 {
+ r := float64(C.PyComplex_RealAsDouble(c(o)))
+ i := float64(C.PyComplex_ImagAsDouble(c(o)))
+ return complex(r, i)
+}
+
+func (c *Complex) String() string {
+ if c == nil {
+ return "<nil>"
+ }
+ return fmt.Sprintf("%v", c.Complex128())
+}
View
@@ -109,6 +109,8 @@ func newObject(obj *C.PyObject) Object {
return (*Code)(o)
case &C.PyCFunction_Type:
return (*CFunction)(o)
+ case &C.PyComplex_Type:
+ return (*Complex)(o)
}
return newBaseObject(obj)
}
View
@@ -504,6 +504,7 @@ PyTypeObject *getBasePyType(PyObject *o) {
if (PyType_Check(o)) return &PyType_Type;
if (PyCode_Check(o)) return &PyCode_Type;
if (PyCFunction_Check(o)) return &PyCFunction_Type;
+ if (PyComplex_Check(o)) return &PyComplex_Type;
return o->ob_type;
}

0 comments on commit 79166a6

Please sign in to comment.