mirror of
https://github.com/roc-lang/roc.git
synced 2025-08-02 03:12:20 +00:00
add string cloning helper
This commit is contained in:
parent
53e7a41f27
commit
ab3a431db7
5 changed files with 36 additions and 0 deletions
|
@ -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.");
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue