##// END OF EJS Templates
rust-utils: add docstrings and doctests for utils.rs...
rust-utils: add docstrings and doctests for utils.rs Differential Revision: https://phab.mercurial-scm.org/D6635

File last commit:

r42816:95113d70 default
r42816:95113d70 default
Show More
utils.rs
76 lines | 1.6 KiB | application/rls-services+xml | RustLexer
Raphaël Gomès
rust-2018: switch hg-core and hg-cpython to rust 2018 edition...
r42815 pub mod files;
Raphaël Gomès
rust-utils: add docstrings and doctests for utils.rs...
r42816 /// Replaces the `from` slice with the `to` slice inside the `buf` slice.
///
/// # Examples
///
/// ```
/// use crate::hg::utils::replace_slice;
/// let mut line = b"I hate writing tests!".to_vec();
/// replace_slice(&mut line, b"hate", b"love");
/// assert_eq!(
/// line,
/// b"I love writing tests!".to_vec()
///);
///
/// ```
Raphaël Gomès
rust-2018: switch hg-core and hg-cpython to rust 2018 edition...
r42815 pub fn replace_slice<T>(buf: &mut [T], from: &[T], to: &[T])
where
T: Clone + PartialEq,
{
Raphaël Gomès
rust-utils: add docstrings and doctests for utils.rs...
r42816 assert_eq!(from.len(), to.len());
if buf.len() < from.len() {
Raphaël Gomès
rust-2018: switch hg-core and hg-cpython to rust 2018 edition...
r42815 return;
}
for i in 0..=buf.len() - from.len() {
if buf[i..].starts_with(from) {
buf[i..(i + from.len())].clone_from_slice(to);
}
}
}
pub trait SliceExt {
Raphaël Gomès
rust-utils: add docstrings and doctests for utils.rs...
r42816 fn trim_end(&self) -> &Self;
fn trim_start(&self) -> &Self;
Raphaël Gomès
rust-2018: switch hg-core and hg-cpython to rust 2018 edition...
r42815 fn trim(&self) -> &Self;
}
fn is_not_whitespace(c: &u8) -> bool {
!(*c as char).is_whitespace()
}
impl SliceExt for [u8] {
fn trim_end(&self) -> &[u8] {
if let Some(last) = self.iter().rposition(is_not_whitespace) {
&self[..last + 1]
} else {
&[]
}
}
Raphaël Gomès
rust-utils: add docstrings and doctests for utils.rs...
r42816 fn trim_start(&self) -> &[u8] {
if let Some(first) = self.iter().position(is_not_whitespace) {
&self[first..]
} else {
&[]
}
}
/// ```
/// use hg::utils::SliceExt;
/// assert_eq!(
/// b" to trim ".trim(),
/// b"to trim"
/// );
/// assert_eq!(
/// b"to trim ".trim(),
/// b"to trim"
/// );
/// assert_eq!(
/// b" to trim".trim(),
/// b"to trim"
/// );
/// ```
fn trim(&self) -> &[u8] {
self.trim_start().trim_end()
}
Raphaël Gomès
rust-2018: switch hg-core and hg-cpython to rust 2018 edition...
r42815 }