-
Notifications
You must be signed in to change notification settings - Fork 1
/
tuple.go
115 lines (95 loc) · 2.21 KB
/
tuple.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package gp
/*
#include <Python.h>
*/
import "C"
import "fmt"
type Tuple struct {
Object
}
func newTuple(obj *cPyObject) Tuple {
return Tuple{newObject(obj)}
}
func MakeTupleWithLen(len int) Tuple {
return newTuple(C.PyTuple_New(C.Py_ssize_t(len)))
}
func MakeTuple(args ...any) Tuple {
tuple := newTuple(C.PyTuple_New(C.Py_ssize_t(len(args))))
for i, arg := range args {
obj := From(arg)
tuple.Set(i, obj)
}
return tuple
}
func (t Tuple) Get(index int) Object {
return newObject(C.PySequence_GetItem(t.obj, C.Py_ssize_t(index)))
}
func (t Tuple) Set(index int, obj Objecter) {
objObj := obj.cpyObj()
C.Py_IncRef(objObj)
r := C.PyTuple_SetItem(t.obj, C.Py_ssize_t(index), objObj)
check(r == 0, fmt.Sprintf("failed to set item %d in tuple", index))
}
func (t Tuple) Len() int {
return int(C.PyTuple_Size(t.obj))
}
func (t Tuple) Slice(low, high int) Tuple {
return newTuple(C.PyTuple_GetSlice(t.obj, C.Py_ssize_t(low), C.Py_ssize_t(high)))
}
func (t Tuple) ParseArgs(addrs ...any) bool {
if len(addrs) > t.Len() {
return false
}
for i, addr := range addrs {
obj := t.Get(i)
switch v := addr.(type) {
// Integer types
case *int:
*v = int(obj.AsLong().Int64())
case *int8:
*v = int8(obj.AsLong().Int64())
case *int16:
*v = int16(obj.AsLong().Int64())
case *int32:
*v = int32(obj.AsLong().Int64())
case *int64:
*v = obj.AsLong().Int64()
case *uint:
*v = uint(obj.AsLong().Int64())
case *uint8:
*v = uint8(obj.AsLong().Int64())
case *uint16:
*v = uint16(obj.AsLong().Int64())
case *uint32:
*v = uint32(obj.AsLong().Int64())
case *uint64:
*v = uint64(obj.AsLong().Int64())
// Floating point types
case *float32:
*v = float32(obj.AsFloat().Float64())
case *float64:
*v = obj.AsFloat().Float64()
// Complex number types
case *complex64:
*v = complex64(obj.AsComplex().Complex128())
case *complex128:
*v = obj.AsComplex().Complex128()
// String types
case *string:
*v = obj.AsStr().String()
case *[]byte:
*v = []byte(obj.AsStr().String())
// Boolean type
case *bool:
*v = obj.AsBool().Bool()
case **cPyObject:
*v = obj.cpyObj()
// Python object
case *Object:
*v = obj
default:
return false
}
}
return true
}