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.
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.
11 use std::cmp::Ordering;
13 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItem_};
14 use syntax::codemap::{CodeMap, Span, BytePos};
17 use comment::FindUncommented;
18 use rewrite::{Rewrite, RewriteContext};
22 // Computes the length of a string's last line, minus offset.
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(),
33 pub fn span_after(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
34 let snippet = codemap.span_to_snippet(original).unwrap();
35 let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
37 original.lo + BytePos(offset as u32)
41 pub fn format_visibility(vis: Visibility) -> &'static str {
43 Visibility::Public => "pub ",
44 Visibility::Inherited => "",
49 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
51 ast::Mutability::MutMutable => "mut ",
52 ast::Mutability::MutImmutable => "",
56 // The width of the first line in s.
58 pub fn first_line_width(s: &str) -> usize {
65 // The width of the last line in s.
67 pub fn last_line_width(s: &str) -> usize {
69 Some(n) => s.len() - n - 1,
75 fn is_skip(meta_item: &MetaItem) -> bool {
76 match meta_item.node {
77 MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,
83 pub fn contains_skip(attrs: &[Attribute]) -> bool {
84 attrs.iter().any(|a| is_skip(&a.node.value))
87 // Find the end of a TyParam
89 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
94 ast::RegionTyParamBound(ref lt) => lt.span,
95 ast::TraitTyParamBound(ref prt, _) => prt.span,
98 .unwrap_or(typaram.span)
103 #[cfg(target_pointer_width="64")]
104 // Based on the trick layed out at
105 // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
106 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
107 x = x.wrapping_sub(1);
118 #[cfg(target_pointer_width="32")]
119 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
120 x = x.wrapping_sub(1);
129 // Macro for deriving implementations of Decodable for enums
131 macro_rules! impl_enum_decodable {
132 ( $e:ident, $( $x:ident ),* ) => {
133 impl ::rustc_serialize::Decodable for $e {
134 fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
135 let s = try!(d.read_str());
138 stringify!($x) => Ok($e::$x),
140 _ => Err(d.error("Bad variant")),
145 impl ::std::str::FromStr for $e {
146 type Err = &'static str;
148 fn from_str(s: &str) -> Result<Self, Self::Err> {
151 stringify!($x) => Ok($e::$x),
153 _ => Err("Bad variant"),
158 impl ::config::ConfigType for $e {
159 fn get_variant_names() -> String {
160 let mut variants = Vec::new();
162 variants.push(stringify!($x));
164 format!("[{}]", variants.join("|"))
170 // Same as try!, but for Option
172 macro_rules! try_opt {
173 ($expr:expr) => (match $expr {
175 None => { return None; }
179 // Wraps string-like values in an Option. Returns Some when the string adheres
180 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
181 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: Indent) -> Option<S> {
183 let snippet = s.as_ref();
185 if !snippet.contains('\n') && snippet.len() > width {
188 let mut lines = snippet.lines();
190 // The caller of this function has already placed `offset`
191 // characters on the first line.
192 let first_line_max_len = try_opt!(max_width.checked_sub(offset.width()));
193 if lines.next().unwrap().len() > first_line_max_len {
197 // The other lines must fit within the maximum width.
198 if lines.find(|line| line.len() > max_width).is_some() {
202 // `width` is the maximum length of the last line, excluding
204 // A special check for the last line, since the caller may
205 // place trailing characters on this line.
206 if snippet.lines().rev().next().unwrap().len() > offset.width() + width {
215 impl Rewrite for String {
216 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
217 wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
221 // Binary search in integer range. Returns the first Ok value returned by the
223 // The callback takes an integer and returns either an Ok, or an Err indicating
224 // whether the `guess' was too high (Ordering::Less), or too low.
225 // This function is guaranteed to try to the hi value first.
226 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
227 where C: Fn(usize) -> Result<T, Ordering>
232 match callback(middle) {
233 Ok(val) => return Some(val),
234 Err(Ordering::Less) => {
241 middle = (hi + lo) / 2;
248 fn bin_search_test() {
252 j if j > 4 => Err(Ordering::Less),
253 j if j < 4 => Err(Ordering::Greater),
258 assert_eq!(Some(()), binary_search(1, 10, &closure));
259 assert_eq!(None, binary_search(1, 3, &closure));
260 assert_eq!(Some(()), binary_search(0, 44, &closure));
261 assert_eq!(Some(()), binary_search(4, 125, &closure));
262 assert_eq!(None, binary_search(6, 100, &closure));
266 fn power_rounding() {
267 assert_eq!(0, round_up_to_power_of_two(0));
268 assert_eq!(1, round_up_to_power_of_two(1));
269 assert_eq!(64, round_up_to_power_of_two(33));
270 assert_eq!(256, round_up_to_power_of_two(256));