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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#![feature(asm)]
#[macro_use] extern crate lazy_static;
extern crate libc;
extern crate term;
extern crate term_size;
use std::any::Any;
use std::fs;
use std::io;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8_unchecked;
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[cfg(test)] use std::thread::sleep;
pub fn filename<'a> (path: &'a str) -> &'a str {
match Path::new (path) .file_name() {
Some (filename) => match filename.to_str() {
Some (fstr) => if fstr.ends_with (".rs") {&fstr[0 .. fstr.len() - 3]} else {fstr},
None => path},
None => path}}
mod gstuff {pub fn filename<'a> (path: &'a str) -> &'a str {super::filename (path)}}
#[macro_export] macro_rules! try_s {
($e: expr) => {match $e {Ok (ok) => ok, Err (err) => {return Err (format! ("{}:{}] {}", ::gstuff::filename (file!()), line!(), err));}}}}
#[macro_export] macro_rules! try_f {
($e: expr) => {match $e {
Ok (ok) => ok,
Err (err) => {return Err (From::from (format! ("{}:{}] {}", ::gstuff::filename (file!()), line!(), err)));}}}}
#[macro_export] macro_rules! try_sp {
($e: expr) => {match $e {&Ok (ref ok) => ok,
&Err (ref err) => {return Err (From::from (format! ("{}:{}] {:?}", ::gstuff::filename (file!()), line!(), err)));}}}}
#[macro_export] macro_rules! try_fu {
($e: expr) => {match $e {
Ok (ok) => ok,
Err (err) => {return Box::new (futures::future::err (From::from (err)))}}}}
#[macro_export] macro_rules! try_fus {
($e: expr) => {match $e {
Ok (ok) => ok,
Err (err) => {return Box::new (futures::future::err (ERRL! ("{}", err)))}}}}
#[macro_export] macro_rules! ERRL {
($format: expr, $($args: tt)+) => {format! (concat! ("{}:{}] ", $format), ::gstuff::filename (file!()), line!(), $($args)+)};
($format: expr) => {format! (concat! ("{}:{}] ", $format), ::gstuff::filename (file!()), line!())}}
#[macro_export] macro_rules! ERR {
($format: expr, $($args: tt)+) => {Err (ERRL! ($format, $($args)+))};
($format: expr) => {Err (ERRL! ($format))}}
lazy_static! {
static ref STATUS_LINE: Mutex<String> = Mutex::new (String::new());
pub static ref ISATTY: bool = unsafe {libc::isatty (1)} != 0;}
pub fn status_line (file: &str, line: u32, status: String) {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
if let Some (mut stdout) = term::stdout() {
if let Ok (mut status_line) = STATUS_LINE.lock() {
let old_hash = {let mut hasher = DefaultHasher::new(); hasher.write (status_line.as_bytes()); hasher.finish()};
status_line.clear();
use std::fmt::Write;
let _ = write! (&mut *status_line, "{}:{}] {}", filename (file), line, status);
let new_hash = {let mut hasher = DefaultHasher::new(); hasher.write (status_line.as_bytes()); hasher.finish()};
if old_hash != new_hash {
match term_size::dimensions() {
Some ((w, _)) if status_line.chars().count() >= w => {
let mut tmp = String::with_capacity (w - 1);
for ch in status_line.chars().take (w - 1) {tmp.push (ch)}
let _ = stdout.get_mut().write (tmp.as_bytes());},
_ => {let _ = stdout.get_mut().write (status_line.as_bytes());}};
let _ = stdout.get_mut().write (b"\x1B[K");
let _ = stdout.carriage_return();
let _ = stdout.get_mut().flush();}}}}
pub fn status_line_clear() {
if let Ok (mut status_line) = STATUS_LINE.lock() {
if *ISATTY && !status_line.is_empty() {
if let Some (mut stdout) = term::stdout() {
status_line.clear();
let _ = stdout.get_mut().write (b"\x1B[K");
let _ = stdout.get_mut().flush();}}}}
pub fn with_status_line (code: &Fn()) {
if let Ok (status_line) = STATUS_LINE.lock() {
if !*ISATTY || status_line.is_empty() {
code()
} else if let Some (mut stdout) = term::stdout() {
let _ = stdout.get_mut().write (b"\x1B[K");
let _ = stdout.get_mut().flush();
code();
let _ = stdout.get_mut().write (status_line.as_bytes());
let _ = stdout.carriage_return();
let _ = stdout.get_mut().flush();}}}
#[test] fn test_status_line() {
with_status_line (&|| println! ("hello world"));}
#[macro_export] macro_rules! gstring {($array: ident, $code: block) => {{
let end = {
let mut $array = ::std::io::Cursor::new (&mut $array[..]);
let $array = &mut $array;
$code;
$array.position() as usize};
unsafe {::std::str::from_utf8_unchecked (&$array[0..end])}}}}
pub fn netstring (at: &[u8]) -> Result<(&[u8], &[u8]), String> {
let length_end = match at.iter().position (|&ch| ch < b'0' || ch > b'9') {Some (l) if l > 0 => l, _ => return ERR! ("No len.")};
match at.get (length_end) {Some (&ch) if ch == b':' => (), _ => return ERR! ("No colon.")};
let length = unsafe {from_utf8_unchecked (&at[0 .. length_end])};
let length: usize = try_s! (length.parse());
let bulk_pos = 0 + length_end + 1;
let bulk_end = bulk_pos + length;
match at.get (bulk_end) {Some (&ch) if ch == b',' => (), _ => return ERR! ("No comma.")}
Ok ((&at[bulk_pos .. bulk_end], &at[bulk_end + 1 ..]))}
#[cfg(unix)]
pub fn with_hostname (visitor: &mut FnMut (&[u8])) -> Result<(), std::io::Error> {
use libc::{size_t, gethostname};
use std::ffi::CStr;
use std::io;
let mut buf = [0; 128];
let rc = unsafe {gethostname (buf.as_mut_ptr(), (buf.len() - 1) as size_t)};
if rc == 0 {
let cs = unsafe {CStr::from_ptr (buf.as_ptr())};
Ok (visitor (cs.to_bytes()))
} else {
Err (io::Error::last_os_error())}}
#[cfg(unix)] #[test] fn test_hostname() {
let mut hostname = String::new();
with_hostname (&mut |bytes| hostname = String::from_utf8_lossy (bytes) .into_owned()) .unwrap();}
pub fn slurp (path: &AsRef<Path>) -> Vec<u8> {
let mut file = match fs::File::open (path) {
Ok (f) => f,
Err (ref err) if err.kind() == io::ErrorKind::NotFound => return Vec::new(),
Err (err) => panic! ("Can't open {:?}: {}", path.as_ref(), err)};
let mut buf = Vec::new();
file.read_to_end (&mut buf) .expect ("!read");
buf}
pub fn slurp_prog (command: &str) -> Result<String, String> {
let output = match Command::new ("dash") .arg ("-c") .arg (command) .output() {
Ok (output) => output,
Err (ref err) if err.kind() == io::ErrorKind::NotFound => {
try_s! (Command::new ("sh") .arg ("-c") .arg (command) .output())},
Err (err) => return ERR! ("{}", err)};
let combined_output: String = if output.stderr.is_empty() {
try_s! (String::from_utf8 (output.stdout))
} else if output.stdout.is_empty() {
try_s! (String::from_utf8 (output.stderr))
} else {
let mut buf = String::with_capacity (output.stderr.len() + output.stdout.len());
buf.push_str (try_s! (std::str::from_utf8 (&output.stderr[..])));
buf.push_str (try_s! (std::str::from_utf8 (&output.stdout[..])));
buf};
if output.status.success() {Ok (combined_output)} else {Err (combined_output)}}
#[test] fn test_slurp_prog() {
let foo = match slurp_prog ("echo foo") {Ok (foo) => foo, Err (err) => panic! ("{}", err)};
assert_eq! (foo.trim(), "foo");}
pub fn cmd (cmd: &str) -> Result<(), String> {
println! ("$ {}", cmd);
let status = try_s! (Command::new ("dash") .arg ("-c") .arg (cmd) .stdout (Stdio::inherit()) .stderr (Stdio::inherit()) .status());
if !status.success() {Err (format! ("Command returned an error status: {}", status))} else {Ok(())}}
pub fn any_to_str<'a> (message: &'a Any) -> Option<&'a str> {
if let Some (message) = message.downcast_ref::<&str>() {return Some (message)}
if let Some (message) = message.downcast_ref::<String>() {return Some (&message[..])}
return None}
pub fn duration_to_float (duration: Duration) -> f64 {
duration.as_secs() as f64 + ((duration.subsec_nanos() as f64) / 1000000000.0)}
pub fn now_float() -> f64 {
let now = SystemTime::now().duration_since (UNIX_EPOCH) .expect ("!duration_since");
duration_to_float (now)}
#[test] fn test_now_float() {
let now = SystemTime::now().duration_since (UNIX_EPOCH) .expect ("!duration_since") .as_secs();
let t1 = now_float();
assert_eq! (now, t1 as u64);
sleep (Duration::from_millis (100));
let t2 = now_float();
let delta = t2 - t1;
assert! (delta > 0.098 && delta < 0.102, "delta: {}", delta);}
pub fn last_modified_sec (path: &AsRef<Path>) -> Result<f64, String> {
let meta = match path.as_ref().metadata() {
Ok (m) => m,
Err (ref err) if err.kind() == std::io::ErrorKind::NotFound => return Ok (0.),
Err (err) => return ERR! ("{}", err)};
let lm = try_s! (meta.modified());
let lm = duration_to_float (try_s! (lm.duration_since (UNIX_EPOCH)));
Ok (lm)}
#[macro_export]
macro_rules! take_until_parse_s (
($i: expr, $remainder: ident! ($($args:tt)*)) => ({
let input: &str = $i;
let mut ret = IResult::Error (error_position! (nom::ErrorKind::Custom (0), input));
for (pos, _) in $i.char_indices() {
match $remainder! (&input[pos..], $($args)*) {
IResult::Done (i,o) => {ret = IResult::Done (i, (&input[0..pos], o)); break},
IResult::Error(_) => continue,
IResult::Incomplete(_) => continue}}
if !ret.is_done() {
if let IResult::Done (i,o) = $remainder! ("", $($args)*) {
ret = IResult::Done (i, (input, o))}}
ret});
($i: expr, $f: expr) => (take_until_parse_s! ($i, call! ($f));););
#[macro_export]
macro_rules! parse_replace_s {
($i: expr, $submac: ident! ($($args:tt)*)) => ({
let input: &str = $i;
let mut output = String::with_capacity (input.len() * 2 + 32);
let mut pos = input;
while let IResult::Done (tail, (head, evaluation)) = take_until_parse_s! (pos, $submac! ($($args)*)) {
output.push_str (head);
output.push_str (&evaluation);
pos = tail;}
output.push_str (pos);
output});
($i: expr, $f: expr) => (parse_replace_s! ($i, call! ($f)););}
#[macro_export]
macro_rules! take_until_find_parse_s (
($i: expr, $starts: expr, $remainder: ident! ($($args:tt)*)) => ({
let input: &str = $i;
let mut ret = IResult::Error (error_position! (nom::ErrorKind::Custom (0), input));
for (pos, _) in $i.match_indices ($starts) {
match $remainder! (&input[pos..], $($args)*) {
IResult::Done (i,o) => {ret = IResult::Done (i, (&input[0..pos], o)); break},
IResult::Error(_) => continue,
IResult::Incomplete(_) => continue}}
ret});
($i: expr, $starts: expr, $f: expr) => (take_until_find_parse_s! ($i, $starts, call! ($f));););
#[macro_export]
macro_rules! find_parse_replace_s {
($i: expr, $starts: expr, $submac: ident! ($($args:tt)*)) => ({
let input: &str = $i;
let mut output = String::with_capacity (input.len() * 2 + 32);
let mut pos = input;
while let IResult::Done (tail, (head, evaluation)) =
take_until_find_parse_s! (pos, $starts, $submac! ($($args)*)) {
output.push_str (head);
output.push_str (&evaluation);
pos = tail;}
output.push_str (pos);
output});
($i: expr, $starts: expr, $f: expr) => (find_parse_replace_s! ($i, $starts, call! ($f)););}
pub fn rdtsc() -> u64 {
#[allow(unused_mut)] unsafe {
let mut low: u32; let mut high: u32;
asm!("rdtsc" : "={eax}" (low), "={edx}" (high));
((high as u64) << 32) | (low as u64)}}
pub struct FileLock<'a> {
pub lock_path: &'a AsRef<Path>,
pub ttl_sec: f64,
pub file: std::fs::File}
impl<'a> FileLock<'a> {
pub fn lock (lock_path: &'a AsRef<Path>, ttl_sec: f64) -> Result<Option<FileLock<'a>>, String> {
let mut cycle = 0u8;
loop {
if cycle > 1 {break Ok (None)}
cycle += 1;
match std::fs::OpenOptions::new().write (true) .create_new (true) .open (lock_path.as_ref()) {
Ok (file) => break Ok (Some (FileLock {lock_path, ttl_sec, file})),
Err (ref ie) if ie.kind() == std::io::ErrorKind::AlreadyExists => {
let lm = match last_modified_sec (lock_path) {
Ok (lm) => lm,
Err (ie) => break ERR! ("Error checking {:?}: {}", lock_path.as_ref(), ie)};
if lm == 0. {continue}
if now_float() - lm > ttl_sec {
if let Err (err) = std::fs::remove_file (lock_path.as_ref()) {break ERR! ("Error removing {:?}: {}", lock_path.as_ref(), err)}
continue}
break Ok (None)},
Err (ie) => break ERR! ("Error creating {:?}: {}", lock_path.as_ref(), ie)}}}
#[cfg(unix)]
pub fn touch (&self) -> Result<(), String> {
let ts = libc::timespec {tv_sec: 0, tv_nsec: libc::UTIME_NOW};
let times = [ts, ts];
use std::os::unix::io::AsRawFd;
let rc = unsafe {libc::futimens (self.file.as_raw_fd(), ×[0])};
if rc != 0 {
let err = std::io::Error::last_os_error();
return ERR! ("Can't touch {:?}: {}", self.lock_path.as_ref(), err)}
Ok(())}}
impl<'a> Drop for FileLock<'a> {
fn drop (&mut self) {
let _ = std::fs::remove_file (self.lock_path);}}
impl<'a> std::fmt::Debug for FileLock<'a> {
fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write! (f, "FileLock ({:?}, {})", self.lock_path.as_ref(), self.ttl_sec)}}
#[derive(Debug)]
pub struct ProcEn {
pub name: String,
pub path: std::path::PathBuf,
pub cmdline: Vec<String>}
impl ProcEn {
pub fn pid (&self) -> Option<u32> {
if let Some (file_name) = self.path.file_name() {
if let Some (file_name) = file_name.to_str() {
if let Ok (pid) = file_name.parse() {
return Some (pid)}}}
None}}
pub struct ProcIt {read_dir: std::fs::ReadDir}
impl ProcIt {
pub fn new() -> ProcIt {
ProcIt {
read_dir: match Path::new ("/proc") .read_dir() {Ok (it) => it, Err (err) => panic! ("!proc: {}", err)}}}}
impl Iterator for ProcIt {
type Item = ProcEn;
fn next (&mut self) -> Option<ProcEn> {
match self.read_dir.next() {
None => return None,
Some (Err (err)) => panic! ("ProcIt] !read_dir: {}", err),
Some (Ok (proc_en)) => {
let file_type = match proc_en.file_type() {Ok (ft) => ft, Err (err) => panic! ("!file_type: {}", err)};
if !file_type.is_dir() {return self.next()}
let name = proc_en.file_name();
let name = match name.to_str() {Some (name) => name, None => panic! ("ProcIt] !to_str")};
if !name.as_bytes().iter().all (|&b| b >= b'0' && b <= b'9') {
return self.next()}
let path = proc_en.path();
let cmdline = String::from_utf8 (slurp (&path.join ("cmdline"))) .expect ("!from_utf8");
if cmdline.is_empty() {return self.next()}
Some (ProcEn {name: name.into(), path: path, cmdline: cmdline.split ('\0') .map (String::from) .collect()})}}}}