Przeglądaj źródła

If the "dump" feature is set, enable an API for dumping to either stdout or a String buffer

Ian Goldberg 1 miesiąc temu
rodzic
commit
3d900c338a
2 zmienionych plików z 36 dodań i 0 usunięć
  1. 34 0
      src/dumper.rs
  2. 2 0
      src/lib.rs

+ 34 - 0
src/dumper.rs

@@ -0,0 +1,34 @@
+#![cfg(feature = "dump")]
+
+//! If the `dump` feature is enabled, expose an API to optionally
+//! allow dumping to a `String` instead of to stdout.  This is
+//! useful if you're running in wasm, which doesn't support stdout.
+
+use std::sync::Mutex;
+
+/// If `None` (the default), dump to stdout.  If `Some(s)`, dump by
+/// appending to `s`
+static DUMP_BUFFER: Mutex<Option<String>> = Mutex::new(None);
+
+/// Enable dumping to a `String` (default is to dump to stdout)
+pub fn dump_to_string() {
+    *DUMP_BUFFER.lock().unwrap() = Some(String::new());
+}
+
+/// Retrieve (and clear) the `String` dump buffer
+pub fn dump_buffer() -> String {
+    let mut b = DUMP_BUFFER.lock().unwrap();
+    match *b {
+        None => String::new(),
+        Some(ref mut buf) => std::mem::take(buf),
+    }
+}
+
+/// Dump a `&str` to either stdout or the `String` buffer
+pub fn dump(s: &str) {
+    let mut b = DUMP_BUFFER.lock().unwrap();
+    match *b {
+        None => { print!("{}", s); }
+        Some(ref mut buf) => { buf.push_str(s); }
+    }
+}

+ 2 - 0
src/lib.rs

@@ -8,3 +8,5 @@ pub use subtle;
 
 pub mod rangeutils;
 pub mod vecutils;
+#[cfg(feature = "dump")]
+pub mod dumper;