]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #8308 : blake2-ppc/rust/str-slice-bytes, r=alexcrichton
authorbors <bors@rust-lang.org>
Tue, 6 Aug 2013 12:26:01 +0000 (05:26 -0700)
committerbors <bors@rust-lang.org>
Tue, 6 Aug 2013 12:26:01 +0000 (05:26 -0700)
`fn slice_bytes` is marked unsafe since it allows violating the valid
string encoding property; but the function did also allow extending the
lifetime of the slice by mistake, since it's returning `&str`.

Use the annotation `slice_bytes<'a>(&'a str, ...) -> &'a str` so
that all uses of `slice_bytes` are region checked correctly.

1  2 
src/libstd/str.rs

diff --combined src/libstd/str.rs
index 95a411a3f96736009bd2461e6dc137a2656badcf,f1a44c4b386396146ef8ec9c0c5f5803857922f0..b4057b85cbfef5cbfae74b54555c359c3e9f5376
@@@ -58,7 -58,7 +58,7 @@@ pub fn from_bytes(vv: &[u8]) -> ~str 
      use str::not_utf8::cond;
  
      if !is_utf8(vv) {
 -        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).get();
 +        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).unwrap();
          cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
                          first_bad_byte as uint))
      } else {
@@@ -75,7 -75,7 +75,7 @@@ pub fn from_bytes_owned(vv: ~[u8]) -> ~
      use str::not_utf8::cond;
  
      if !is_utf8(vv) {
 -        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).get();
 +        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).unwrap();
          cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
                          first_bad_byte as uint))
      } else {
@@@ -885,7 -885,7 +885,7 @@@ pub mod raw 
      /// If begin is greater than end.
      /// If end is greater than the length of the string.
      #[inline]
-     pub unsafe fn slice_bytes(s: &str, begin: uint, end: uint) -> &str {
+     pub unsafe fn slice_bytes<'a>(s: &'a str, begin: uint, end: uint) -> &'a str {
          do s.as_imm_buf |sbuf, n| {
               assert!((begin <= end));
               assert!((end <= n));
          let new_len = s.len() + 1;
          s.reserve_at_least(new_len);
          do s.as_mut_buf |buf, len| {
 -            *ptr::mut_offset(buf, len as int) = b;
 +            *ptr::mut_offset(buf, (len-1) as int) = b;
          }
          set_len(&mut *s, new_len);
      }
@@@ -2825,13 -2825,6 +2825,13 @@@ mod tests 
          assert!(!"   _   ".is_whitespace());
      }
  
 +    #[test]
 +    fn test_push_byte() {
 +        let mut s = ~"ABC";
 +        unsafe{raw::push_byte(&mut s, 'D' as u8)};
 +        assert_eq!(s, ~"ABCD");
 +    }
 +
      #[test]
      fn test_shift_byte() {
          let mut s = ~"ABC";