support bytes() built-in

This commit is contained in:
lyon 2022-05-26 15:46:34 +08:00
parent 2b9452a5b5
commit 6b63c13bef
5 changed files with 50 additions and 1 deletions

View File

@ -25,6 +25,7 @@ class SysObj(BaseObj):
def hex(self, val: int) -> str: ...
def ord(self, val: str) -> int: ...
def chr(self, val: int) -> str: ...
def bytes(self, val: any) -> bytes: ...
class RangeObj(TinyObj):

View File

@ -295,3 +295,24 @@ char* PikaStdLib_SysObj_chr(PikaObj* self, int val) {
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
Arg* PikaStdLib_SysObj_bytes(PikaObj* self, Arg* val) {
ArgType type = arg_getType(val);
if (ARG_TYPE_INT == type) {
int size = arg_getInt(val);
/* src is NULL so the bytes are all '\0' */
Arg* bytes = arg_setBytes(NULL, "", NULL, size);
return bytes;
}
if (ARG_TYPE_BYTES == type) {
return arg_copy(val);
}
if (ARG_TYPE_STRING == type) {
int size = strGetSize(arg_getStr(val));
Arg* bytes = arg_setBytes(NULL, "", (uint8_t*)arg_getStr(val), size);
return bytes;
}
obj_setErrorCode(self, 1);
__platform_printf("Error: input arg type not supported.\r\n");
return arg_setNull(NULL);
}

View File

@ -25,6 +25,7 @@ class SysObj(BaseObj):
def hex(self, val: int) -> str: ...
def ord(self, val: str) -> int: ...
def chr(self, val: int) -> str: ...
def bytes(self, val: any) -> bytes: ...
class RangeObj(TinyObj):

View File

@ -295,3 +295,24 @@ char* PikaStdLib_SysObj_chr(PikaObj* self, int val) {
obj_setStr(self, "__buf", buff);
return obj_getStr(self, "__buf");
}
Arg* PikaStdLib_SysObj_bytes(PikaObj* self, Arg* val) {
ArgType type = arg_getType(val);
if (ARG_TYPE_INT == type) {
int size = arg_getInt(val);
/* src is NULL so the bytes are all '\0' */
Arg* bytes = arg_setBytes(NULL, "", NULL, size);
return bytes;
}
if (ARG_TYPE_BYTES == type) {
return arg_copy(val);
}
if (ARG_TYPE_STRING == type) {
int size = strGetSize(arg_getStr(val));
Arg* bytes = arg_setBytes(NULL, "", (uint8_t*)arg_getStr(val), size);
return bytes;
}
obj_setErrorCode(self, 1);
__platform_printf("Error: input arg type not supported.\r\n");
return arg_setNull(NULL);
}

View File

@ -133,9 +133,14 @@ Arg* arg_setBytes(Arg* self, char* name, uint8_t* src, size_t size) {
self = arg_setName(self, name);
self = arg_setType(self, ARG_TYPE_BYTES);
void* dir = arg_getContent(self);
/* set content all to 0 */
__platform_memset(dir, 0, size + sizeof(size_t));
__platform_memcpy(dir, &size, sizeof(size_t));
__platform_memcpy((void*)((uintptr_t)dir + sizeof(size_t)), src, size);
/* set init value */
if (NULL != src) {
__platform_memcpy((void*)((uintptr_t)dir + sizeof(size_t)), src, size);
}
return self;
}