add string cloning helper

This commit is contained in:
Folkert 2022-07-23 00:08:01 +02:00
parent 53e7a41f27
commit ab3a431db7
No known key found for this signature in database
GPG key ID: 1F17F6FFD112B97C
5 changed files with 36 additions and 0 deletions

View file

@ -143,6 +143,7 @@ comptime {
exportStrFn(str.strTrim, "trim");
exportStrFn(str.strTrimLeft, "trim_left");
exportStrFn(str.strTrimRight, "trim_right");
exportStrFn(str.strCloneTo, "clone_to");
inline for (INTEGERS) |T| {
str.exportFromInt(T, ROC_BUILTINS ++ "." ++ STR ++ ".from_int.");

View file

@ -2521,3 +2521,35 @@ test "getScalarUnsafe" {
try expectEqual(result.scalar, @intCast(u32, expected));
try expectEqual(result.bytesParsed, 1);
}
pub fn strCloneTo(
ptr: [*]u8,
offset: usize,
string: RocStr,
) callconv(.C) usize {
const WIDTH: usize = @sizeOf(RocStr);
if (string.isSmallStr()) {
const array: [@sizeOf(RocStr)]u8 = @bitCast([@sizeOf(RocStr)]u8, string);
var i: usize = 0;
while (i < array.len) : (i += 1) {
ptr[offset + i] = array[i];
}
return offset + WIDTH;
} else {
const slice = string.asSlice();
var relative = string;
relative.str_bytes = @intToPtr(?[*]u8, offset + WIDTH); // i.e. just after the string struct
// write the string struct
const array = relative.asArray();
@memcpy(ptr + offset, &array, WIDTH);
// write the string bytes just after the struct
@memcpy(ptr + offset + WIDTH, slice.ptr, slice.len);
return offset + WIDTH + slice.len;
}
}