support slice for str and bytes, tested

This commit is contained in:
lyon 2022-05-30 14:35:44 +08:00
parent a41d206509
commit d96d01d8a9
3 changed files with 58 additions and 0 deletions

View File

@ -366,5 +366,25 @@ Arg* PikaStdLib_SysObj___slice__(PikaObj* self,
return sliced_arg;
}
if (ARG_TYPE_BYTES == arg_getType(obj)) {
Arg* sliced_arg = arg_setBytes(NULL, "", NULL, 0);
for (int i = start_i; i < end_i; i++) {
Arg* i_arg = arg_setInt(NULL, "", i);
Arg* item_arg = PikaStdLib_SysObj___get__(self, i_arg, obj);
uint8_t* bytes_origin = arg_getBytes(sliced_arg);
size_t size_origin = arg_getBytesSize(sliced_arg);
Arg* sliced_arg_new = arg_setBytes(NULL, "", NULL, size_origin + 1);
__platform_memcpy(arg_getBytes(sliced_arg_new), bytes_origin,
size_origin);
__platform_memcpy(arg_getBytes(sliced_arg_new) + size_origin,
arg_getBytes(item_arg), 1);
arg_deinit(sliced_arg);
sliced_arg = sliced_arg_new;
arg_deinit(item_arg);
arg_deinit(i_arg);
}
return sliced_arg;
}
return arg_setNull(NULL);
}

View File

@ -366,5 +366,25 @@ Arg* PikaStdLib_SysObj___slice__(PikaObj* self,
return sliced_arg;
}
if (ARG_TYPE_BYTES == arg_getType(obj)) {
Arg* sliced_arg = arg_setBytes(NULL, "", NULL, 0);
for (int i = start_i; i < end_i; i++) {
Arg* i_arg = arg_setInt(NULL, "", i);
Arg* item_arg = PikaStdLib_SysObj___get__(self, i_arg, obj);
uint8_t* bytes_origin = arg_getBytes(sliced_arg);
size_t size_origin = arg_getBytesSize(sliced_arg);
Arg* sliced_arg_new = arg_setBytes(NULL, "", NULL, size_origin + 1);
__platform_memcpy(arg_getBytes(sliced_arg_new), bytes_origin,
size_origin);
__platform_memcpy(arg_getBytes(sliced_arg_new) + size_origin,
arg_getBytes(item_arg), 1);
arg_deinit(sliced_arg);
sliced_arg = sliced_arg_new;
arg_deinit(item_arg);
arg_deinit(i_arg);
}
return sliced_arg;
}
return arg_setNull(NULL);
}

View File

@ -1959,3 +1959,21 @@ TEST(pikaMain, slice1) {
obj_deinit(self);
EXPECT_EQ(pikaMemNow(), 0);
}
TEST(pikaMain, slice2) {
/* init */
pikaMemInfo.heapUsedMax = 0;
/* run */
PikaObj* self = newRootObj("pikaMain", New_PikaMain);
__platform_printf("BEGIN\r\n");
obj_run(self,
"b'test'[1:3]\n"
);
/* assert */
EXPECT_STREQ(log_buff[1], "\\x73");
EXPECT_STREQ(log_buff[2], "\\x65");
EXPECT_STREQ(log_buff[4], "BEGIN\r\n");
/* deinit */
obj_deinit(self);
EXPECT_EQ(pikaMemNow(), 0);
}