dumper.rs 1018 B

12345678910111213141516171819202122232425262728293031323334
  1. #![cfg(feature = "dump")]
  2. //! If the `dump` feature is enabled, expose an API to optionally
  3. //! allow dumping to a `String` instead of to stdout. This is
  4. //! useful if you're running in wasm, which doesn't support stdout.
  5. use std::sync::Mutex;
  6. /// If `None` (the default), dump to stdout. If `Some(s)`, dump by
  7. /// appending to `s`
  8. static DUMP_BUFFER: Mutex<Option<String>> = Mutex::new(None);
  9. /// Enable dumping to a `String` (default is to dump to stdout)
  10. pub fn dump_to_string() {
  11. *DUMP_BUFFER.lock().unwrap() = Some(String::new());
  12. }
  13. /// Retrieve (and clear) the `String` dump buffer
  14. pub fn dump_buffer() -> String {
  15. let mut b = DUMP_BUFFER.lock().unwrap();
  16. match *b {
  17. None => String::new(),
  18. Some(ref mut buf) => std::mem::take(buf),
  19. }
  20. }
  21. /// Dump a `&str` to either stdout or the `String` buffer
  22. pub fn dump(s: &str) {
  23. let mut b = DUMP_BUFFER.lock().unwrap();
  24. match *b {
  25. None => { print!("{}", s); }
  26. Some(ref mut buf) => { buf.push_str(s); }
  27. }
  28. }