common.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use std::{fs,io};
  2. pub const VERSION: &'static str = "0.0";
  3. pub const AUTHOR: &'static str =
  4. "Getty Ritter <rrecutils@infinitenegativeutility.com>";
  5. pub enum Input {
  6. Stdin(io::BufReader<io::Stdin>),
  7. File(io::BufReader<fs::File>),
  8. }
  9. impl io::Read for Input {
  10. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  11. match self {
  12. &mut Input::Stdin(ref mut stdin) =>
  13. stdin.read(buf),
  14. &mut Input::File(ref mut file) =>
  15. file.read(buf),
  16. }
  17. }
  18. }
  19. impl io::BufRead for Input {
  20. fn fill_buf(&mut self) -> io::Result<&[u8]> {
  21. match self {
  22. &mut Input::Stdin(ref mut stdin) =>
  23. stdin.fill_buf(),
  24. &mut Input::File(ref mut file) =>
  25. file.fill_buf(),
  26. }
  27. }
  28. fn consume(&mut self, amt: usize) {
  29. match self {
  30. &mut Input::Stdin(ref mut stdin) =>
  31. stdin.consume(amt),
  32. &mut Input::File(ref mut file) =>
  33. file.consume(amt),
  34. }
  35. }
  36. }
  37. pub fn input_from_spec<'a>(
  38. spec: Option<&'a str>
  39. ) -> io::Result<Input> {
  40. match spec.unwrap_or("-") {
  41. "-" => Ok(Input::Stdin(io::BufReader::new(io::stdin()))),
  42. path => {
  43. let f = fs::File::open(path)?;
  44. Ok(Input::File(io::BufReader::new(f)))
  45. }
  46. }
  47. }
  48. pub fn output_from_spec<'a>(
  49. spec: Option<&'a str>
  50. ) -> io::Result<Box<io::Write>>
  51. {
  52. match spec.unwrap_or("-") {
  53. "-" => Ok(Box::new(io::stdout())),
  54. path => Ok(Box::new(fs::File::open(path)?)),
  55. }
  56. }