Skip to content

Commit 75bcd7e

Browse files
bors[bot]dbrgn
andauthored
Merge #152
152: Implement Vec::starts_with and Vec::ends_with r=korken89 a=dbrgn Implementation mostly copied from `std`. The logic should be covered by documentation tests, so no separate unit tests were added. Co-authored-by: Danilo Bargen <[email protected]>
2 parents 253cd89 + 5e32bf7 commit 75bcd7e

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/vec.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,54 @@ where
366366
pub(crate) fn is_full(&self) -> bool {
367367
self.0.is_full()
368368
}
369+
370+
/// Returns `true` if `needle` is a prefix of the Vec.
371+
///
372+
/// Always returns `true` if `needle` is an empty slice.
373+
///
374+
/// # Examples
375+
///
376+
/// ```
377+
/// use heapless::Vec;
378+
/// use heapless::consts::*;
379+
///
380+
/// let v: Vec<_, U8> = Vec::from_slice(b"abc").unwrap();
381+
/// assert_eq!(v.starts_with(b""), true);
382+
/// assert_eq!(v.starts_with(b"ab"), true);
383+
/// assert_eq!(v.starts_with(b"bc"), false);
384+
/// ```
385+
#[inline]
386+
pub fn starts_with(&self, needle: &[T]) -> bool
387+
where
388+
T: PartialEq,
389+
{
390+
let n = needle.len();
391+
self.len() >= n && needle == &self[..n]
392+
}
393+
394+
/// Returns `true` if `needle` is a suffix of the Vec.
395+
///
396+
/// Always returns `true` if `needle` is an empty slice.
397+
///
398+
/// # Examples
399+
///
400+
/// ```
401+
/// use heapless::Vec;
402+
/// use heapless::consts::*;
403+
///
404+
/// let v: Vec<_, U8> = Vec::from_slice(b"abc").unwrap();
405+
/// assert_eq!(v.ends_with(b""), true);
406+
/// assert_eq!(v.ends_with(b"ab"), false);
407+
/// assert_eq!(v.ends_with(b"bc"), true);
408+
/// ```
409+
#[inline]
410+
pub fn ends_with(&self, needle: &[T]) -> bool
411+
where
412+
T: PartialEq,
413+
{
414+
let (v, n) = (self.len(), needle.len());
415+
v >= n && needle == &self[v - n..]
416+
}
369417
}
370418

371419
impl<T, N> Default for Vec<T, N>
@@ -960,4 +1008,28 @@ mod tests {
9601008
// Slice too large
9611009
assert!(Vec::<u8, U2>::from_slice(&[1, 2, 3]).is_err());
9621010
}
1011+
1012+
#[test]
1013+
fn starts_with() {
1014+
let v: Vec<_, U8> = Vec::from_slice(b"ab").unwrap();
1015+
assert!(v.starts_with(&[]));
1016+
assert!(v.starts_with(b""));
1017+
assert!(v.starts_with(b"a"));
1018+
assert!(v.starts_with(b"ab"));
1019+
assert!(!v.starts_with(b"abc"));
1020+
assert!(!v.starts_with(b"ba"));
1021+
assert!(!v.starts_with(b"b"));
1022+
}
1023+
1024+
#[test]
1025+
fn ends_with() {
1026+
let v: Vec<_, U8> = Vec::from_slice(b"ab").unwrap();
1027+
assert!(v.ends_with(&[]));
1028+
assert!(v.ends_with(b""));
1029+
assert!(v.ends_with(b"b"));
1030+
assert!(v.ends_with(b"ab"));
1031+
assert!(!v.ends_with(b"abc"));
1032+
assert!(!v.ends_with(b"ba"));
1033+
assert!(!v.ends_with(b"a"));
1034+
}
9631035
}

0 commit comments

Comments
 (0)