support and tested char() and ord() builtin-fun

This commit is contained in:
lyon 2022-05-25 15:53:39 +08:00
parent 09bb50a98c
commit d3fd9512b4
5 changed files with 68 additions and 6 deletions

View File

@ -23,6 +23,8 @@ class SysObj(BaseObj):
def list(self) -> any: ...
def dict(self) -> any: ...
def hex(self, val: int) -> str: ...
def ord(self, val: str) -> int: ...
def chr(self, val: int) -> str: ...
class RangeObj(TinyObj):

View File

@ -281,3 +281,17 @@ char* PikaStdLib_SysObj_hex(PikaObj *self, int val){
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
int PikaStdLib_SysObj_ord(PikaObj* self, char* val) {
return (int)val[0];
}
char* PikaStdLib_SysObj_chr(PikaObj* self, int val) {
char buff[PIKA_SPRINTF_BUFF_SIZE] = {0};
char to_str[] = "0";
to_str[0] = val;
__platform_sprintf(buff, "%s", to_str);
/* load the string from stack to heap */
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}

View File

@ -23,6 +23,8 @@ class SysObj(BaseObj):
def list(self) -> any: ...
def dict(self) -> any: ...
def hex(self, val: int) -> str: ...
def ord(self, val: str) -> int: ...
def chr(self, val: int) -> str: ...
class RangeObj(TinyObj):

View File

@ -281,3 +281,17 @@ char* PikaStdLib_SysObj_hex(PikaObj *self, int val){
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
int PikaStdLib_SysObj_ord(PikaObj* self, char* val) {
return (int)val[0];
}
char* PikaStdLib_SysObj_chr(PikaObj* self, int val) {
char buff[PIKA_SPRINTF_BUFF_SIZE] = {0};
char to_str[] = "0";
to_str[0] = val;
__platform_sprintf(buff, "%s", to_str);
/* load the string from stack to heap */
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}

View File

@ -1805,3 +1805,33 @@ TEST(pikaMain, builtin_hex) {
obj_deinit(self);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(pikaMain, builtin_ord) {
/* init */
pikaMemInfo.heapUsedMax = 0;
/* run */
PikaObj* self = newRootObj("pikaMain", New_PikaMain);
__platform_printf("BEGIN\r\n");
obj_run(self, "ord('a')\n");
/* assert */
EXPECT_STREQ(log_buff[1], "BEGIN\r\n");
EXPECT_STREQ(log_buff[0], "97\r\n");
/* deinit */
obj_deinit(self);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(pikaMain, builtin_chr) {
/* init */
pikaMemInfo.heapUsedMax = 0;
/* run */
PikaObj* self = newRootObj("pikaMain", New_PikaMain);
__platform_printf("BEGIN\r\n");
obj_run(self, "chr(97)\n");
/* assert */
EXPECT_STREQ(log_buff[1], "BEGIN\r\n");
EXPECT_STREQ(log_buff[0], "a\r\n");
/* deinit */
obj_deinit(self);
EXPECT_EQ(pikaMemNow(), 0);
}