]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #309 from marcusklaas/array-literals
[rust.git] / src / utils.rs
1 // Copyright 2015 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 use std::cmp::Ordering;
12
13 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItem_};
14 use syntax::codemap::{CodeMap, Span, BytePos};
15
16 use comment::FindUncommented;
17 use rewrite::{Rewrite, RewriteContext};
18
19 use SKIP_ANNOTATION;
20
21 // Computes the length of a string's last line, minus offset.
22 #[inline]
23 pub fn extra_offset(text: &str, offset: usize) -> usize {
24     match text.rfind('\n') {
25         // 1 for newline character
26         Some(idx) => text.len() - idx - 1 - offset,
27         None => text.len(),
28     }
29 }
30
31 #[inline]
32 pub fn span_after(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
33     let snippet = codemap.span_to_snippet(original).unwrap();
34
35     original.lo + BytePos(snippet.find_uncommented(needle).unwrap() as u32 + 1)
36 }
37
38 #[inline]
39 pub fn make_indent(width: usize) -> String {
40     let mut indent = String::with_capacity(width);
41     for _ in 0..width {
42         indent.push(' ')
43     }
44     indent
45 }
46
47 #[inline]
48 pub fn format_visibility(vis: Visibility) -> &'static str {
49     match vis {
50         Visibility::Public => "pub ",
51         Visibility::Inherited => "",
52     }
53 }
54
55 #[inline]
56 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
57     match mutability {
58         ast::Mutability::MutMutable => "mut ",
59         ast::Mutability::MutImmutable => "",
60     }
61 }
62
63 // The width of the first line in s.
64 #[inline]
65 pub fn first_line_width(s: &str) -> usize {
66     match s.find('\n') {
67         Some(n) => n,
68         None => s.len(),
69     }
70 }
71
72 // The width of the last line in s.
73 #[inline]
74 pub fn last_line_width(s: &str) -> usize {
75     match s.rfind('\n') {
76         Some(n) => s.len() - n - 1,
77         None => s.len(),
78     }
79 }
80
81 #[inline]
82 fn is_skip(meta_item: &MetaItem) -> bool {
83     match meta_item.node {
84         MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,
85         _ => false,
86     }
87 }
88
89 #[inline]
90 pub fn contains_skip(attrs: &[Attribute]) -> bool {
91     attrs.iter().any(|a| is_skip(&a.node.value))
92 }
93
94 // Find the end of a TyParam
95 #[inline]
96 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
97     typaram.bounds
98            .last()
99            .map(|bound| {
100                match *bound {
101                    ast::RegionTyParamBound(ref lt) => lt.span,
102                    ast::TraitTyParamBound(ref prt, _) => prt.span,
103                }
104            })
105            .unwrap_or(typaram.span)
106            .hi
107 }
108
109 #[inline]
110 #[cfg(target_pointer_width="64")]
111 // Based on the trick layed out at
112 // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
113 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
114     x = x.wrapping_sub(1);
115     x |= x >> 1;
116     x |= x >> 2;
117     x |= x >> 4;
118     x |= x >> 8;
119     x |= x >> 16;
120     x |= x >> 32;
121     x.wrapping_add(1)
122 }
123
124 #[inline]
125 #[cfg(target_pointer_width="32")]
126 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
127     x = x.wrapping_sub(1);
128     x |= x >> 1;
129     x |= x >> 2;
130     x |= x >> 4;
131     x |= x >> 8;
132     x |= x >> 16;
133     x.wrapping_add(1)
134 }
135
136 // Macro for deriving implementations of Decodable for enums
137 #[macro_export]
138 macro_rules! impl_enum_decodable {
139     ( $e:ident, $( $x:ident ),* ) => {
140         impl ::rustc_serialize::Decodable for $e {
141             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
142                 let s = try!(d.read_str());
143                 match &*s {
144                     $(
145                         stringify!($x) => Ok($e::$x),
146                     )*
147                     _ => Err(d.error("Bad variant")),
148                 }
149             }
150         }
151
152         impl ::std::str::FromStr for $e {
153             type Err = &'static str;
154
155             fn from_str(s: &str) -> Result<Self, Self::Err> {
156                 match &*s {
157                     $(
158                         stringify!($x) => Ok($e::$x),
159                     )*
160                     _ => Err("Bad variant"),
161                 }
162             }
163         }
164     };
165 }
166
167 // Same as try!, but for Option
168 #[macro_export]
169 macro_rules! try_opt {
170     ($expr:expr) => (match $expr {
171         Some(val) => val,
172         None => { return None; }
173     })
174 }
175
176 // Wraps string-like values in an Option. Returns Some when the string adheres
177 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
178 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: usize) -> Option<S> {
179     {
180         let snippet = s.as_ref();
181
182         if !snippet.contains('\n') && snippet.len() > width {
183             return None;
184         } else {
185             let mut lines = snippet.lines();
186
187             // The caller of this function has already placed `offset`
188             // characters on the first line.
189             let first_line_max_len = try_opt!(max_width.checked_sub(offset));
190             if lines.next().unwrap().len() > first_line_max_len {
191                 return None;
192             }
193
194             // The other lines must fit within the maximum width.
195             if lines.find(|line| line.len() > max_width).is_some() {
196                 return None;
197             }
198
199             // `width` is the maximum length of the last line, excluding
200             // indentation.
201             // A special check for the last line, since the caller may
202             // place trailing characters on this line.
203             if snippet.lines().rev().next().unwrap().len() > offset + width {
204                 return None;
205             }
206         }
207     }
208
209     Some(s)
210 }
211
212 impl Rewrite for String {
213     fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
214         wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
215     }
216 }
217
218 // Binary search in integer range. Returns the first Ok value returned by the
219 // callback.
220 // The callback takes an integer and returns either an Ok, or an Err indicating
221 // whether the `guess' was too high (Ordering::Less), or too low.
222 // This function is guaranteed to try to the hi value first.
223 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
224     where C: Fn(usize) -> Result<T, Ordering>
225 {
226     let mut middle = hi;
227
228     while lo <= hi {
229         match callback(middle) {
230             Ok(val) => return Some(val),
231             Err(Ordering::Less) => {
232                 hi = middle - 1;
233             }
234             Err(..) => {
235                 lo = middle + 1;
236             }
237         }
238         middle = (hi + lo) / 2;
239     }
240
241     None
242 }
243
244 #[test]
245 fn bin_search_test() {
246     let closure = |i| {
247         match i {
248             4 => Ok(()),
249             j if j > 4 => Err(Ordering::Less),
250             j if j < 4 => Err(Ordering::Greater),
251             _ => unreachable!(),
252         }
253     };
254
255     assert_eq!(Some(()), binary_search(1, 10, &closure));
256     assert_eq!(None, binary_search(1, 3, &closure));
257     assert_eq!(Some(()), binary_search(0, 44, &closure));
258     assert_eq!(Some(()), binary_search(4, 125, &closure));
259     assert_eq!(None, binary_search(6, 100, &closure));
260 }
261
262 #[test]
263 fn power_rounding() {
264     assert_eq!(0, round_up_to_power_of_two(0));
265     assert_eq!(1, round_up_to_power_of_two(1));
266     assert_eq!(64, round_up_to_power_of_two(33));
267     assert_eq!(256, round_up_to_power_of_two(256));
268 }