Skip to content

Commit 4eda964

Browse files
committed
Implement ord()
1 parent 8cc57c1 commit 4eda964

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

builtin/builtin.go

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"github.com/ncw/gpython/py"
77
"github.com/ncw/gpython/vm"
8+
"unicode/utf8"
89
)
910

1011
const builtin_doc = `Built-in functions, exceptions, and other objects.
@@ -46,7 +47,7 @@ func init() {
4647
// py.NewMethod("min", builtin_min, 0, min_doc),
4748
py.NewMethod("next", builtin_next, 0, next_doc),
4849
// py.NewMethod("oct", builtin_oct, 0, oct_doc),
49-
// py.NewMethod("ord", builtin_ord, 0, ord_doc),
50+
py.NewMethod("ord", builtin_ord, 0, ord_doc),
5051
py.NewMethod("pow", builtin_pow, 0, pow_doc),
5152
py.NewMethod("print", builtin_print, 0, print_doc),
5253
// py.NewMethod("repr", builtin_repr, 0, repr_doc),
@@ -349,3 +350,36 @@ func builtin___import__(self py.Object, args py.Tuple, kwargs py.StringDict) py.
349350
py.ParseTupleAndKeywords(args, kwargs, "U|OOOi:__import__", kwlist, &name, &globals, &locals, &fromlist, &level)
350351
return py.ImportModuleLevelObject(name, globals, locals, fromlist, int(level.(py.Int)))
351352
}
353+
354+
const ord_doc = `ord(c) -> integer
355+
356+
Return the integer ordinal of a one-character string.`
357+
358+
func builtin_ord(self, obj py.Object) py.Object {
359+
var size int
360+
switch x := obj.(type) {
361+
case py.Bytes:
362+
size = len(x)
363+
if len(x) == 1 {
364+
return py.Int(x[0])
365+
}
366+
case py.String:
367+
var rune rune
368+
rune, size = utf8.DecodeRuneInString(string(x))
369+
if len(x) == size && rune != utf8.RuneError {
370+
return py.Int(rune)
371+
}
372+
//case py.ByteArray:
373+
// XXX Hopefully this is temporary
374+
// FIXME implement
375+
// size = PyByteArray_GET_SIZE(obj)
376+
// if size == 1 {
377+
// ord = (long)((char) * PyByteArray_AS_STRING(obj))
378+
// return PyLong_FromLong(ord)
379+
// }
380+
default:
381+
panic(py.ExceptionNewf(py.TypeError, "ord() expected string of length 1, but %s found", obj.Type().Name))
382+
}
383+
384+
panic(py.ExceptionNewf(py.TypeError, "ord() expected a character, but string of length %zd found", size))
385+
}

0 commit comments

Comments
 (0)