##// END OF EJS Templates
rust-utils: add docstrings and doctests for utils.rs...
Raphaël Gomès -
r42829:5672bb73 default
parent child Browse files
Show More
@@ -15,7 +15,7 b' pub use dirstate::{'
15 15 DirstateVec,
16 16 };
17 17 mod filepatterns;
18 mod utils;
18 pub mod utils;
19 19
20 20 pub use filepatterns::{
21 21 build_single_regex, read_pattern_file, PatternSyntax, PatternTuple,
@@ -1,10 +1,25 b''
1 1 pub mod files;
2 2
3 /// Replaces the `from` slice with the `to` slice inside the `buf` slice.
4 ///
5 /// # Examples
6 ///
7 /// ```
8 /// use crate::hg::utils::replace_slice;
9 /// let mut line = b"I hate writing tests!".to_vec();
10 /// replace_slice(&mut line, b"hate", b"love");
11 /// assert_eq!(
12 /// line,
13 /// b"I love writing tests!".to_vec()
14 ///);
15 ///
16 /// ```
3 17 pub fn replace_slice<T>(buf: &mut [T], from: &[T], to: &[T])
4 18 where
5 19 T: Clone + PartialEq,
6 20 {
7 if buf.len() < from.len() || from.len() != to.len() {
21 assert_eq!(from.len(), to.len());
22 if buf.len() < from.len() {
8 23 return;
9 24 }
10 25 for i in 0..=buf.len() - from.len() {
@@ -15,8 +30,9 b' where'
15 30 }
16 31
17 32 pub trait SliceExt {
33 fn trim_end(&self) -> &Self;
34 fn trim_start(&self) -> &Self;
18 35 fn trim(&self) -> &Self;
19 fn trim_end(&self) -> &Self;
20 36 }
21 37
22 38 fn is_not_whitespace(c: &u8) -> bool {
@@ -24,17 +40,6 b' fn is_not_whitespace(c: &u8) -> bool {'
24 40 }
25 41
26 42 impl SliceExt for [u8] {
27 fn trim(&self) -> &[u8] {
28 if let Some(first) = self.iter().position(is_not_whitespace) {
29 if let Some(last) = self.iter().rposition(is_not_whitespace) {
30 &self[first..last + 1]
31 } else {
32 unreachable!();
33 }
34 } else {
35 &[]
36 }
37 }
38 43 fn trim_end(&self) -> &[u8] {
39 44 if let Some(last) = self.iter().rposition(is_not_whitespace) {
40 45 &self[..last + 1]
@@ -42,4 +47,30 b' impl SliceExt for [u8] {'
42 47 &[]
43 48 }
44 49 }
50 fn trim_start(&self) -> &[u8] {
51 if let Some(first) = self.iter().position(is_not_whitespace) {
52 &self[first..]
53 } else {
54 &[]
55 }
56 }
57
58 /// ```
59 /// use hg::utils::SliceExt;
60 /// assert_eq!(
61 /// b" to trim ".trim(),
62 /// b"to trim"
63 /// );
64 /// assert_eq!(
65 /// b"to trim ".trim(),
66 /// b"to trim"
67 /// );
68 /// assert_eq!(
69 /// b" to trim".trim(),
70 /// b"to trim"
71 /// );
72 /// ```
73 fn trim(&self) -> &[u8] {
74 self.trim_start().trim_end()
75 }
45 76 }
General Comments 0
You need to be logged in to leave comments. Login now