Skip to content

Commit cd9d833

Browse files
committed
Implement slice_strip feature
1 parent d462551 commit cd9d833

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/libcore/slice/mod.rs

+62
Original file line numberDiff line numberDiff line change
@@ -1459,6 +1459,68 @@ impl<T> [T] {
14591459
m >= n && needle == &self[m - n..]
14601460
}
14611461

1462+
/// Returns a subslice with the prefix removed.
1463+
///
1464+
/// This method returns [`None`] if slice does not start with `prefix`.
1465+
/// Also it returns the original slice if `prefix` is an empty slice.
1466+
///
1467+
/// # Examples
1468+
///
1469+
/// ```
1470+
/// #![feature(slice_strip)]
1471+
/// let v = &[10, 40, 30];
1472+
/// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
1473+
/// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
1474+
/// assert_eq!(v.strip_prefix(&[50]), None);
1475+
/// assert_eq!(v.strip_prefix(&[10, 50]), None);
1476+
/// ```
1477+
#[must_use = "returns the subslice without modifying the original"]
1478+
#[unstable(feature = "slice_strip", issue = "73413")]
1479+
pub fn strip_prefix(&self, prefix: &[T]) -> Option<&[T]>
1480+
where
1481+
T: PartialEq,
1482+
{
1483+
let n = prefix.len();
1484+
if n <= self.len() {
1485+
let (head, tail) = self.split_at(n);
1486+
if head == prefix {
1487+
return Some(tail);
1488+
}
1489+
}
1490+
None
1491+
}
1492+
1493+
/// Returns a subslice with the suffix removed.
1494+
///
1495+
/// This method returns [`None`] if slice does not end with `suffix`.
1496+
/// Also it returns the original slice if `suffix` is an empty slice
1497+
///
1498+
/// # Examples
1499+
///
1500+
/// ```
1501+
/// #![feature(slice_strip)]
1502+
/// let v = &[10, 40, 30];
1503+
/// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
1504+
/// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
1505+
/// assert_eq!(v.strip_suffix(&[50]), None);
1506+
/// assert_eq!(v.strip_suffix(&[50, 30]), None);
1507+
/// ```
1508+
#[must_use = "returns the subslice without modifying the original"]
1509+
#[unstable(feature = "slice_strip", issue = "73413")]
1510+
pub fn strip_suffix(&self, suffix: &[T]) -> Option<&[T]>
1511+
where
1512+
T: PartialEq,
1513+
{
1514+
let (len, n) = (self.len(), suffix.len());
1515+
if n <= len {
1516+
let (head, tail) = self.split_at(len - n);
1517+
if tail == suffix {
1518+
return Some(head);
1519+
}
1520+
}
1521+
None
1522+
}
1523+
14621524
/// Binary searches this sorted slice for a given element.
14631525
///
14641526
/// If the value is found then [`Result::Ok`] is returned, containing the

0 commit comments

Comments
 (0)