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