Eliminate @memcpy from Str.trim functions

This commit is contained in:
Richard Feldman 2022-07-18 10:28:30 -04:00
parent b6b66b883a
commit 7e446d1b0d
No known key found for this signature in database
GPG key ID: 7E4127D1E4241798

View file

@ -1977,16 +1977,18 @@ pub fn strTrim(string: RocStr) callconv(.C) RocStr {
const small_or_shared = new_len <= SMALL_STR_MAX_LENGTH or !string.isRefcountOne(); const small_or_shared = new_len <= SMALL_STR_MAX_LENGTH or !string.isRefcountOne();
if (small_or_shared) { if (small_or_shared) {
return RocStr.init(string.asU8ptr() + leading_bytes, new_len); return RocStr.init(string.asU8ptr() + leading_bytes, new_len);
} } else {
// nonempty, large, and unique: shift everything over in-place if necessary.
// nonempty, large, and unique: // Note: must use memmove over memcpy, because the bytes definitely overlap!
if (leading_bytes > 0) { if (leading_bytes > 0) {
var i: usize = 0; // Zig doesn't seem to have `memmove` in the stdlib anymore; this is based on:
while (i < new_len) : (i += 1) { // https://github.com/ziglang/zig/blob/52ba2c3a43a88a4db30cff47f2f3eff8c3d5be19/lib/std/special/c.zig#L115
const dest = bytes_ptr + i; // Copyright Andrew Kelley, MIT licensed.
const source = dest + leading_bytes; const src = bytes_ptr + leading_bytes;
@memcpy(dest, source, 1); var index: usize = 0;
while (index != new_len) : (index += 1) {
bytes_ptr[index] = src[index];
} }
} }
@ -1995,6 +1997,7 @@ pub fn strTrim(string: RocStr) callconv(.C) RocStr {
return new_string; return new_string;
} }
}
return RocStr.empty(); return RocStr.empty();
} }
@ -2014,16 +2017,18 @@ pub fn strTrimLeft(string: RocStr) callconv(.C) RocStr {
const small_or_shared = new_len <= SMALL_STR_MAX_LENGTH or !string.isRefcountOne(); const small_or_shared = new_len <= SMALL_STR_MAX_LENGTH or !string.isRefcountOne();
if (small_or_shared) { if (small_or_shared) {
return RocStr.init(string.asU8ptr() + leading_bytes, new_len); return RocStr.init(string.asU8ptr() + leading_bytes, new_len);
} } else {
// nonempty, large, and unique: shift everything over in-place if necessary.
// nonempty, large, and unique: // Note: must use memmove over memcpy, because the bytes definitely overlap!
if (leading_bytes > 0) { if (leading_bytes > 0) {
var i: usize = 0; // Zig doesn't seem to have `memmove` in the stdlib anymore; this is based on:
while (i < new_len) : (i += 1) { // https://github.com/ziglang/zig/blob/52ba2c3a43a88a4db30cff47f2f3eff8c3d5be19/lib/std/special/c.zig#L115
const dest = bytes_ptr + i; // Copyright Andrew Kelley, MIT licensed.
const source = dest + leading_bytes; const src = bytes_ptr + leading_bytes;
@memcpy(dest, source, 1); var index: usize = 0;
while (index != new_len) : (index += 1) {
bytes_ptr[index] = src[index];
} }
} }
@ -2032,6 +2037,7 @@ pub fn strTrimLeft(string: RocStr) callconv(.C) RocStr {
return new_string; return new_string;
} }
}
return RocStr.empty(); return RocStr.empty();
} }