]> git.lizzy.rs Git - rust.git/blob - tests/ui/slow_vector_initialization.rs
Add unsafe set_len initialization
[rust.git] / tests / ui / slow_vector_initialization.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use std::iter::repeat;
11
12 fn main() {
13     resize_vector();
14     extend_vector();
15     mixed_extend_resize_vector();
16     unsafe_vector();
17 }
18
19 fn extend_vector() {
20     // Extend with constant expression
21     let len = 300;
22     let mut vec1 = Vec::with_capacity(len);
23     vec1.extend(repeat(0).take(len));
24
25     // Extend with len expression
26     let mut vec2 = Vec::with_capacity(len - 10);
27     vec2.extend(repeat(0).take(len - 10));
28
29     // Extend with mismatching expression should not be warned
30     let mut vec3 = Vec::with_capacity(24322);
31     vec3.extend(repeat(0).take(2));
32 }
33
34 fn mixed_extend_resize_vector() {
35     // Mismatching len
36     let mut mismatching_len = Vec::with_capacity(30);
37
38     // Slow initialization
39     let mut resized_vec = Vec::with_capacity(30);
40     let mut extend_vec = Vec::with_capacity(30);
41
42     resized_vec.resize(30, 0);
43     mismatching_len.extend(repeat(0).take(40));
44     extend_vec.extend(repeat(0).take(30));
45 }
46
47 fn resize_vector() {
48     // Resize with constant expression
49     let len = 300;
50     let mut vec1 = Vec::with_capacity(len);
51     vec1.resize(len, 0);
52
53     // Resize mismatch len
54     let mut vec2 = Vec::with_capacity(200);
55     vec2.resize(10, 0);
56
57     // Resize with len expression
58     let mut vec3 = Vec::with_capacity(len - 10);
59     vec3.resize(len - 10, 0);
60
61     // Reinitialization should be warned
62     vec1 = Vec::with_capacity(10);
63     vec1.resize(10, 0);
64 }
65
66 fn unsafe_vector() {
67     let mut unsafe_vec: Vec<u8> = Vec::with_capacity(200);
68
69     unsafe {
70         unsafe_vec.set_len(200);
71     }
72 }