虽然Rust提供str.as_bytes
,但我希望将一个字符串复制到一个固定大小的缓冲区中,其中只有完整的unicode-scalar-values被复制到缓冲区中,而是被一个写入的null终止符截断。最后,用C语言,我称之为utf8
知道strlcpy
(即 - 它复制到固定大小的缓冲区并确保其空终止)。 / p>
这是我提出的功能,但我希望在Rust中有更好的方法:
// return the number of bytes written to
pub fn strlcpy_utf8(utf8_dst: &mut [u8], str_src: &str) -> usize {
let utf8_dst_len = utf8_dst.len();
if utf8_dst_len == 0 {
return 0;
}
let mut index: usize = 0;
if utf8_dst_len > 1 {
let mut utf8_buf: [u8; 4] = [0; 4];
for c in str_src.chars() {
let len_utf8 = c.len_utf8();
let index_next = index + len_utf8;
c.encode_utf8(&mut utf8_buf);
if index_next >= utf8_dst_len {
break;
}
utf8_dst[index..index_next].clone_from_slice(&utf8_buf[0..len_utf8]);
index = index_next;
}
}
utf8_dst[index] = 0;
return index + 1;
}
注意):我意识到这不理想,因为多个UCS
可能组成一个字形,但结果至少能够解码回{{1 }}
答案 0 :(得分:4)
Rust str
有一个方便的方法char_indices
,当你需要知道实际的字符边界时。这会立即简化你的功能:
pub fn strlcpy_utf8(utf8_dst: &mut [u8], str_src: &str) -> usize {
let utf8_dst_len = utf8_dst.len();
if utf8_dst_len == 0 {
return 0;
}
let mut last_index = 0;
for (idx, _) in str_src.char_indices() {
if (idx+1) > utf8_dst_len {
break;
}
last_index = idx;
}
utf8_dst[0..last_index].copy_from_slice(&str_src.as_bytes()[0..last_index]);
utf8_dst[last_index] = 0;
return last_index + 1;
}
然而,除了复制之外,你实际上并不需要迭代每个字符,因为事实证明在UTF8中很容易找到边界; Rust有str::is_char_boundary()
。这让你可以从最后向后看:
pub fn strlcpy_utf8(utf8_dst: &mut [u8], str_src: &str) -> usize {
let utf8_dst_len = utf8_dst.len();
if utf8_dst_len == 0 {
return 0;
}
let mut last_index = min(utf8_dst_len-1, str_src.len());
while last_index > 0 && !str_src.is_char_boundary(last_index) {
last_index -= 1;
}
utf8_dst[0..last_index].copy_from_slice(&str_src.as_bytes()[0..last_index]);
utf8_dst[last_index] = 0;
return last_index + 1;
}
答案 1 :(得分:-1)
根据Chris Emerson的回答和@ Matthieu-m建议删除冗余支票。
// returns the number of bytes written to
pub fn strlcpy_utf8(utf8_dst: &mut [u8], str_src: &str) -> usize {
let utf8_dst_len = utf8_dst.len();
if utf8_dst_len == 0 {
return 0;
}
// truncate if 'str_src' is too long
let mut last_index = str_src.len();
if last_index >= utf8_dst_len {
last_index = utf8_dst_len - 1;
// no need to check last_index > 0 here,
// is_char_boundary covers that case
while !str_src.is_char_boundary(last_index) {
last_index -= 1;
}
}
utf8_dst[0..last_index].clone_from_slice(&str_src.as_bytes()[0..last_index]);
utf8_dst[last_index] = 0;
return last_index + 1;
}
@ChrisEmerson:我发布了这个,因为它是我将用于我的项目的代码,如果你愿意,可以随时更新你的答案,我会删除这个答案。