@@ -366,6 +366,54 @@ where
366
366
pub ( crate ) fn is_full ( & self ) -> bool {
367
367
self . 0 . is_full ( )
368
368
}
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
+ }
369
417
}
370
418
371
419
impl < T , N > Default for Vec < T , N >
@@ -960,4 +1008,28 @@ mod tests {
960
1008
// Slice too large
961
1009
assert ! ( Vec :: <u8 , U2 >:: from_slice( & [ 1 , 2 , 3 ] ) . is_err( ) ) ;
962
1010
}
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
+ }
963
1035
}
0 commit comments