]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/common.rs
add inline attributes to stage 0 methods
[rust.git] / src / librustc / util / common.rs
1 // Copyright 2012-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 #![allow(non_camel_case_types)]
12
13 use std::cell::{RefCell, Cell};
14 use std::collections::HashMap;
15 use std::ffi::CString;
16 use std::fmt::Debug;
17 use std::hash::{Hash, BuildHasher};
18 use std::iter::repeat;
19 use std::path::Path;
20 use std::time::{Duration, Instant};
21
22 // The name of the associated type for `Fn` return types
23 pub const FN_OUTPUT_NAME: &'static str = "Output";
24
25 // Useful type to use with `Result<>` indicate that an error has already
26 // been reported to the user, so no need to continue checking.
27 #[derive(Clone, Copy, Debug)]
28 pub struct ErrorReported;
29
30 thread_local!(static TIME_DEPTH: Cell<usize> = Cell::new(0));
31
32 /// Read the current depth of `time()` calls. This is used to
33 /// encourage indentation across threads.
34 pub fn time_depth() -> usize {
35     TIME_DEPTH.with(|slot| slot.get())
36 }
37
38 /// Set the current depth of `time()` calls. The idea is to call
39 /// `set_time_depth()` with the result from `time_depth()` in the
40 /// parent thread.
41 pub fn set_time_depth(depth: usize) {
42     TIME_DEPTH.with(|slot| slot.set(depth));
43 }
44
45 pub fn time<T, F>(do_it: bool, what: &str, f: F) -> T where
46     F: FnOnce() -> T,
47 {
48     if !do_it { return f(); }
49
50     let old = TIME_DEPTH.with(|slot| {
51         let r = slot.get();
52         slot.set(r + 1);
53         r
54     });
55
56     let start = Instant::now();
57     let rv = f();
58     let dur = start.elapsed();
59
60     let mem_string = match get_resident() {
61         Some(n) => {
62             let mb = n as f64 / 1_000_000.0;
63             format!("; rss: {}MB", mb.round() as usize)
64         }
65         None => "".to_owned(),
66     };
67     println!("{}time: {}{}\t{}",
68              repeat("  ").take(old).collect::<String>(),
69              duration_to_secs_str(dur),
70              mem_string,
71              what);
72
73     TIME_DEPTH.with(|slot| slot.set(old));
74
75     rv
76 }
77
78 // Hack up our own formatting for the duration to make it easier for scripts
79 // to parse (always use the same number of decimal places and the same unit).
80 pub fn duration_to_secs_str(dur: Duration) -> String {
81     const NANOS_PER_SEC: f64 = 1_000_000_000.0;
82     let secs = dur.as_secs() as f64 +
83                dur.subsec_nanos() as f64 / NANOS_PER_SEC;
84
85     format!("{:.3}", secs)
86 }
87
88 pub fn to_readable_str(mut val: usize) -> String {
89     let mut groups = vec![];
90     loop {
91         let group = val % 1000;
92
93         val /= 1000;
94
95         if val == 0 {
96             groups.push(format!("{}", group));
97             break
98         } else {
99             groups.push(format!("{:03}", group));
100         }
101     }
102
103     groups.reverse();
104
105     groups.join("_")
106 }
107
108 pub fn record_time<T, F>(accu: &Cell<Duration>, f: F) -> T where
109     F: FnOnce() -> T,
110 {
111     let start = Instant::now();
112     let rv = f();
113     let duration = start.elapsed();
114     accu.set(duration + accu.get());
115     rv
116 }
117
118 // Like std::macros::try!, but for Option<>.
119 macro_rules! option_try(
120     ($e:expr) => (match $e { Some(e) => e, None => return None })
121 );
122
123 // Memory reporting
124 #[cfg(unix)]
125 fn get_resident() -> Option<usize> {
126     use std::fs::File;
127     use std::io::Read;
128
129     let field = 1;
130     let mut f = option_try!(File::open("/proc/self/statm").ok());
131     let mut contents = String::new();
132     option_try!(f.read_to_string(&mut contents).ok());
133     let s = option_try!(contents.split_whitespace().nth(field));
134     let npages = option_try!(s.parse::<usize>().ok());
135     Some(npages * 4096)
136 }
137
138 #[cfg(windows)]
139 fn get_resident() -> Option<usize> {
140     type BOOL = i32;
141     type DWORD = u32;
142     type HANDLE = *mut u8;
143     use libc::size_t;
144     use std::mem;
145     #[repr(C)] #[allow(non_snake_case)]
146     struct PROCESS_MEMORY_COUNTERS {
147         cb: DWORD,
148         PageFaultCount: DWORD,
149         PeakWorkingSetSize: size_t,
150         WorkingSetSize: size_t,
151         QuotaPeakPagedPoolUsage: size_t,
152         QuotaPagedPoolUsage: size_t,
153         QuotaPeakNonPagedPoolUsage: size_t,
154         QuotaNonPagedPoolUsage: size_t,
155         PagefileUsage: size_t,
156         PeakPagefileUsage: size_t,
157     }
158     type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
159     #[link(name = "psapi")]
160     extern "system" {
161         fn GetCurrentProcess() -> HANDLE;
162         fn GetProcessMemoryInfo(Process: HANDLE,
163                                 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
164                                 cb: DWORD) -> BOOL;
165     }
166     let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { mem::zeroed() };
167     pmc.cb = mem::size_of_val(&pmc) as DWORD;
168     match unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) } {
169         0 => None,
170         _ => Some(pmc.WorkingSetSize as usize),
171     }
172 }
173
174 pub fn indent<R, F>(op: F) -> R where
175     R: Debug,
176     F: FnOnce() -> R,
177 {
178     // Use in conjunction with the log post-processor like `src/etc/indenter`
179     // to make debug output more readable.
180     debug!(">>");
181     let r = op();
182     debug!("<< (Result = {:?})", r);
183     r
184 }
185
186 pub struct Indenter {
187     _cannot_construct_outside_of_this_module: ()
188 }
189
190 impl Drop for Indenter {
191     fn drop(&mut self) { debug!("<<"); }
192 }
193
194 pub fn indenter() -> Indenter {
195     debug!(">>");
196     Indenter { _cannot_construct_outside_of_this_module: () }
197 }
198
199 pub trait MemoizationMap {
200     type Key: Clone;
201     type Value: Clone;
202
203     /// If `key` is present in the map, return the valuee,
204     /// otherwise invoke `op` and store the value in the map.
205     ///
206     /// NB: if the receiver is a `DepTrackingMap`, special care is
207     /// needed in the `op` to ensure that the correct edges are
208     /// added into the dep graph. See the `DepTrackingMap` impl for
209     /// more details!
210     fn memoize<OP>(&self, key: Self::Key, op: OP) -> Self::Value
211         where OP: FnOnce() -> Self::Value;
212 }
213
214 impl<K, V, S> MemoizationMap for RefCell<HashMap<K,V,S>>
215     where K: Hash+Eq+Clone, V: Clone, S: BuildHasher
216 {
217     type Key = K;
218     type Value = V;
219
220     fn memoize<OP>(&self, key: K, op: OP) -> V
221         where OP: FnOnce() -> V
222     {
223         let result = self.borrow().get(&key).cloned();
224         match result {
225             Some(result) => result,
226             None => {
227                 let result = op();
228                 self.borrow_mut().insert(key, result.clone());
229                 result
230             }
231         }
232     }
233 }
234
235 #[cfg(unix)]
236 pub fn path2cstr(p: &Path) -> CString {
237     use std::os::unix::prelude::*;
238     use std::ffi::OsStr;
239     let p: &OsStr = p.as_ref();
240     CString::new(p.as_bytes()).unwrap()
241 }
242 #[cfg(windows)]
243 pub fn path2cstr(p: &Path) -> CString {
244     CString::new(p.to_str().unwrap()).unwrap()
245 }
246
247
248 #[test]
249 fn test_to_readable_str() {
250     assert_eq!("0", to_readable_str(0));
251     assert_eq!("1", to_readable_str(1));
252     assert_eq!("99", to_readable_str(99));
253     assert_eq!("999", to_readable_str(999));
254     assert_eq!("1_000", to_readable_str(1_000));
255     assert_eq!("1_001", to_readable_str(1_001));
256     assert_eq!("999_999", to_readable_str(999_999));
257     assert_eq!("1_000_000", to_readable_str(1_000_000));
258     assert_eq!("1_234_567", to_readable_str(1_234_567));
259 }