]> git.lizzy.rs Git - rust.git/blob - src/test/ui/methods/method-mut-self-modifies-mut-slice-lvalue.rs
move an `assert!` to the right place
[rust.git] / src / test / ui / methods / method-mut-self-modifies-mut-slice-lvalue.rs
1 // run-pass
2 // Test that an `&mut self` method, when invoked on a place whose
3 // type is `&mut [u8]`, passes in a pointer to the place and not a
4 // temporary. Issue #19147.
5
6 use std::slice;
7 use std::cmp;
8
9 trait MyWriter {
10     fn my_write(&mut self, buf: &[u8]) -> Result<(), ()>;
11 }
12
13 impl<'a> MyWriter for &'a mut [u8] {
14     fn my_write(&mut self, buf: &[u8]) -> Result<(), ()> {
15         let amt = cmp::min(self.len(), buf.len());
16         self[..amt].clone_from_slice(&buf[..amt]);
17
18         let write_len = buf.len();
19         unsafe {
20             *self = slice::from_raw_parts_mut(
21                 self.as_mut_ptr().add(write_len),
22                 self.len() - write_len
23             );
24         }
25
26         Ok(())
27     }
28 }
29
30 fn main() {
31     let mut buf = [0; 6];
32
33     {
34         let mut writer: &mut [_] = &mut buf;
35         writer.my_write(&[0, 1, 2]).unwrap();
36         writer.my_write(&[3, 4, 5]).unwrap();
37     }
38
39     // If `my_write` is not modifying `buf` in place, then we will
40     // wind up with `[3, 4, 5, 0, 0, 0]` because the first call to
41     // `my_write()` doesn't update the starting point for the write.
42
43     assert_eq!(buf, [0, 1, 2, 3, 4, 5]);
44 }