]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/method-mut-self-modifies-mut-slice-lvalue.rs
cleanup: s/impl Copy/#[derive(Copy)]/g
[rust.git] / src / test / run-pass / method-mut-self-modifies-mut-slice-lvalue.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Test that an `&mut self` method, when invoked on an lvalue whose
12 // type is `&mut [u8]`, passes in a pointer to the lvalue and not a
13 // temporary. Issue #19147.
14
15 use std::raw;
16 use std::mem;
17 use std::slice;
18 use std::io::IoResult;
19
20 trait MyWriter {
21     fn my_write(&mut self, buf: &[u8]) -> IoResult<()>;
22 }
23
24 impl<'a> MyWriter for &'a mut [u8] {
25     fn my_write(&mut self, buf: &[u8]) -> IoResult<()> {
26         slice::bytes::copy_memory(*self, buf);
27
28         let write_len = buf.len();
29         unsafe {
30             *self = mem::transmute(raw::Slice {
31                 data: self.as_ptr().offset(write_len as int),
32                 len: self.len() - write_len,
33             });
34         }
35
36         Ok(())
37     }
38 }
39
40 fn main() {
41     let mut buf = [0_u8; 6];
42
43     {
44         let mut writer = buf.as_mut_slice();
45         writer.my_write(&[0, 1, 2]).unwrap();
46         writer.my_write(&[3, 4, 5]).unwrap();
47     }
48
49     // If `my_write` is not modifying `buf` in place, then we will
50     // wind up with `[3, 4, 5, 0, 0, 0]` because the first call to
51     // `my_write()` doesn't update the starting point for the write.
52
53     assert_eq!(buf, [0, 1, 2, 3, 4, 5]);
54 }