io.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. use std::io;
  2. use sha1::Sha1;
  3. use log::*;
  4. /// Write wrapper that computes Sha1 checksums of the data written.
  5. pub struct HashWrite<'a, W: io::Write> {
  6. writer: W,
  7. hash: &'a mut Sha1
  8. }
  9. impl <'a, W: io::Write> HashWrite<'a, W> {
  10. /// Create a hash writer
  11. pub fn create(base: W, hash: &'a mut Sha1) -> HashWrite<'a, W> {
  12. HashWrite {
  13. writer: base,
  14. hash: hash
  15. }
  16. }
  17. }
  18. impl <'a, W: io::Write> io::Write for HashWrite<'a, W> {
  19. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  20. self.hash.update(buf);
  21. self.writer.write(buf)
  22. }
  23. fn flush(&mut self) -> io::Result<()> {
  24. self.writer.flush()
  25. }
  26. }
  27. /// Read wrapper that computes Sha1 checksums of the data read.
  28. pub struct HashRead<'a, R: io::Read> {
  29. reader: R,
  30. hash: &'a mut Sha1
  31. }
  32. impl <'a, R: io::Read> HashRead<'a, R> {
  33. /// Create a hash reader
  34. pub fn create(base: R, hash: &'a mut Sha1) -> HashRead<'a, R> {
  35. HashRead {
  36. reader: base,
  37. hash: hash
  38. }
  39. }
  40. }
  41. impl <'a, R: io::Read> io::Read for HashRead<'a, R> {
  42. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  43. let n = self.reader.read(buf)?;
  44. self.hash.update(&buf[0..n]);
  45. Ok(n)
  46. }
  47. }
  48. pub struct DelimPrinter<'a> {
  49. delim: &'a [u8],
  50. end: &'a [u8],
  51. first: bool
  52. }
  53. impl <'a> DelimPrinter<'a> {
  54. pub fn new(delim: &'a str, end: &'a str) -> DelimPrinter<'a> {
  55. DelimPrinter {
  56. delim: delim.as_bytes(),
  57. end: end.as_bytes(),
  58. first: true
  59. }
  60. }
  61. pub fn preface<W: io::Write>(&mut self, w: &mut W) -> io::Result<bool> {
  62. if self.first {
  63. self.first = false;
  64. Ok(false)
  65. } else {
  66. w.write_all(self.delim)?;
  67. Ok(true)
  68. }
  69. }
  70. pub fn end<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
  71. w.write_all(self.end)?;
  72. self.first = true;
  73. Ok(())
  74. }
  75. }