|
5 | 5 | "fmt"
|
6 | 6 | "github.com/ncw/gpython/py"
|
7 | 7 | "github.com/ncw/gpython/vm"
|
| 8 | + "unicode/utf8" |
8 | 9 | )
|
9 | 10 |
|
10 | 11 | const builtin_doc = `Built-in functions, exceptions, and other objects.
|
@@ -46,7 +47,7 @@ func init() {
|
46 | 47 | // py.NewMethod("min", builtin_min, 0, min_doc),
|
47 | 48 | py.NewMethod("next", builtin_next, 0, next_doc),
|
48 | 49 | // 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), |
50 | 51 | py.NewMethod("pow", builtin_pow, 0, pow_doc),
|
51 | 52 | py.NewMethod("print", builtin_print, 0, print_doc),
|
52 | 53 | // 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.
|
349 | 350 | py.ParseTupleAndKeywords(args, kwargs, "U|OOOi:__import__", kwlist, &name, &globals, &locals, &fromlist, &level)
|
350 | 351 | return py.ImportModuleLevelObject(name, globals, locals, fromlist, int(level.(py.Int)))
|
351 | 352 | }
|
| 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