-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlib.rs
71 lines (64 loc) · 2.08 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::hash::Hasher;
/// ```
/// let commit_hash = exec("git rev-parse HEAD")?;
/// ```
pub fn exec(command: &str) -> std::io::Result<String> {
let args = command.split_ascii_whitespace().collect::<Vec<_>>();
let (cmd, args) = args.split_first().unwrap();
let output = std::process::Command::new(cmd).args(args).output()?;
if !output.status.success() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("command {:?} returned non-zero code", command),
));
}
let stdout = String::from_utf8(output.stdout)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
Ok(stdout.trim().to_string())
}
pub fn stable_hash<T: std::hash::Hash>(value: &T) -> u64 {
#![allow(deprecated)]
let mut hasher = std::hash::SipHasher::default();
std::hash::Hash::hash(value, &mut hasher);
hasher.finish()
}
// Source:
// <https://github.com/rust-lang/rust/blob/1.55.0/library/core/src/slice/sort.rs#L559-L573>
pub fn random_numbers() -> impl Iterator<Item = u32> {
let mut random = 92u32;
std::iter::repeat_with(move || {
random ^= random << 13;
random ^= random >> 17;
random ^= random << 5;
random
})
}
pub fn random_seed() -> u64 {
std::hash::BuildHasher::build_hasher(&std::collections::hash_map::RandomState::new()).finish()
}
#[must_use]
pub fn timeit(label: impl Into<String>) -> impl Drop {
let label = label.into();
let now = std::time::Instant::now();
defer(move || eprintln!("{}: {:.2?}", label, now.elapsed()))
}
#[must_use]
pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
struct D<F: FnOnce()>(Option<F>);
impl<F: FnOnce()> Drop for D<F> {
fn drop(&mut self) {
if let Some(f) = self.0.take() {
f()
}
}
}
D(Some(f))
}
/// Appends formatted string to a `String`.
#[macro_export]
macro_rules! format_to {
($buf:expr) => ();
($buf:expr, $lit:literal $($arg:tt)*) => {
{ use ::std::fmt::Write as _; let _ = ::std::write!($buf, $lit $($arg)*); }
};
}