diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 9f925f9d371a6..37d2868db2bb4 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -223,10 +223,33 @@ pub trait ImmutableSlice<'a, T> { /// order code that indicates whether its argument is `Less`, /// `Equal` or `Greater` the desired target. /// - /// If the value is found then `Found` is returned, containing the - /// index of the matching element; if the value is not found then + /// If a matching value is found then returns `Found`, containing + /// the index for the matched element; if no match is found then /// `NotFound` is returned, containing the index where a matching /// element could be inserted while maintaining sorted order. + /// + /// # Example + /// + /// Looks up a series of four elements. The first is found, with a + /// uniquely determined position; the second and third are not + /// found; the fourth could match any position in `[1,4]`. + /// + /// ```rust + /// use std::slice::{Found, NotFound}; + /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = s.as_slice(); + /// let seek = 13; + /// assert_eq!(Found(9), s.binary_search(|probe| probe.cmp(&seek))); + /// let seek = 4; + /// assert_eq!(NotFound(7), s.binary_search(|probe| probe.cmp(&seek))); + /// let seek = 100; + /// assert_eq!(NotFound(13), s.binary_search(|probe| probe.cmp(&seek))); + /// let seek = 1; + /// assert!(match s.binary_search(|probe| probe.cmp(&seek)) { + /// Found(idx) if 1 <= idx && idx <= 4 => true, + /// _ => false, + /// }); + /// ``` #[unstable = "waiting on unboxed closures"] fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult; @@ -1043,6 +1066,26 @@ pub trait ImmutableOrdSlice { /// index of the matching element; if the value is not found then /// `NotFound` is returned, containing the index where a matching /// element could be inserted while maintaining sorted order. + /// + /// # Example + /// + /// Looks up a series of four elements. The first is found, with a + /// uniquely determined position; the second and third are not + /// found; the fourth could match any position in `[1,4]`. + /// + /// ```rust + /// use std::slice::{Found, NotFound}; + /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; + /// let s = s.as_slice(); + /// + /// assert_eq!(Found(9), s.binary_search_elem(&13)); + /// assert_eq!(NotFound(7), s.binary_search_elem(&4)); + /// assert_eq!(NotFound(13), s.binary_search_elem(&100)); + /// assert!(match s.binary_search_elem(&1) { + /// Found(idx) if 1 <= idx && idx <= 4 => true, + /// _ => false, + /// }); + /// ``` #[unstable = "name likely to change"] fn binary_search_elem(&self, x: &T) -> BinarySearchResult; }