Move join_strings into wcstringutil.rs

On the C++ side it lives in wcstringutil.cpp.  We should probably keep
it there until we have ported the entirety of that file.
This commit is contained in:
Johannes Altmanninger 2023-03-26 13:34:51 +02:00
parent 4f14b8dc7b
commit ed3a0b2bc3
4 changed files with 32 additions and 29 deletions

View file

@ -49,6 +49,7 @@ mod wait_handle;
mod wchar;
mod wchar_ext;
mod wchar_ffi;
mod wcstringutil;
mod wgetopt;
mod wutil;

View file

@ -0,0 +1,30 @@
//! Helper functions for working with wcstring.
use crate::wchar::{wstr, WString};
/// Joins strings with a separator.
pub fn join_strings(strs: &[&wstr], sep: char) -> WString {
if strs.is_empty() {
return WString::new();
}
let capacity = strs.iter().fold(0, |acc, s| acc + s.len()) + strs.len() - 1;
let mut result = WString::with_capacity(capacity);
for (i, s) in strs.iter().enumerate() {
if i > 0 {
result.push(sep);
}
result.push_utfstr(s);
}
result
}
#[test]
fn test_join_strings() {
use crate::wchar::L;
assert_eq!(join_strings(&[], '/'), "");
assert_eq!(join_strings(&[L!("foo")], '/'), "foo");
assert_eq!(
join_strings(&[L!("foo"), L!("bar"), L!("baz")], '/'),
"foo/bar/baz"
);
}

View file

@ -6,7 +6,6 @@ pub mod wcstod;
pub mod wcstoi;
mod wrealpath;
use crate::wchar::{wstr, WString};
pub(crate) use gettext::{wgettext, wgettext_fmt};
pub use normalize_path::*;
pub(crate) use printf::sprintf;
@ -29,30 +28,3 @@ pub fn perror(s: &str) {
let _ = stderr.write_all(slice);
let _ = stderr.write_all(b"\n");
}
/// Joins strings with a separator.
pub fn join_strings(strs: &[&wstr], sep: char) -> WString {
if strs.is_empty() {
return WString::new();
}
let capacity = strs.iter().fold(0, |acc, s| acc + s.len()) + strs.len() - 1;
let mut result = WString::with_capacity(capacity);
for (i, s) in strs.iter().enumerate() {
if i > 0 {
result.push(sep);
}
result.push_utfstr(s);
}
result
}
#[test]
fn test_join_strings() {
use crate::wchar::L;
assert_eq!(join_strings(&[], '/'), "");
assert_eq!(join_strings(&[L!("foo")], '/'), "foo");
assert_eq!(
join_strings(&[L!("foo"), L!("bar"), L!("baz")], '/'),
"foo/bar/baz"
);
}

View file

@ -1,5 +1,5 @@
use crate::wchar::{wstr, WString, L};
use crate::wutil::join_strings;
use crate::wcstringutil::join_strings;
/// Given an input path, "normalize" it:
/// 1. Collapse multiple /s into a single /, except maybe at the beginning.