chiark / gitweb /
server: boundary_finder plumbing
[hippotat.git] / src / multipart.rs
index 82ce4ac4af73e775871604a36945edc998129ba5..b858039c73e782c6993442548e70bf08c9f9be99 100644 (file)
@@ -11,9 +11,12 @@ pub struct Component<'b> {
 }
 
 #[derive(Debug)]
+#[derive(Eq,PartialEq,Ord,PartialOrd,Hash)]
 #[allow(non_camel_case_types)]
 pub enum PartName { m, d, Other }
 
+pub type BoundaryFinder = memchr::memmem::Finder<'static>;
+
 #[throws(AE)]
 pub fn process_component<'b>(warnings: &mut Warnings,
                              after_leader: &'b [u8], expected: PartName)
@@ -72,3 +75,63 @@ pub fn process_component<'b>(warnings: &mut Warnings,
 
   Some(Component { name: part_name.unwrap_or(expected), payload_start: rhs })
 }
+
+pub struct MetadataFieldIterator<'b> {
+  buf: &'b [u8],
+  last: Option<usize>,
+  iter: memchr::Memchr<'b>,
+}
+
+impl<'b> MetadataFieldIterator<'b> {
+  pub fn new(buf: &'b [u8]) -> Self { Self {
+    buf,
+    last: Some(0),
+    iter: memchr::Memchr::new(b'\n', buf),
+  } }
+
+  #[throws(AE)]
+  pub fn need_next(&mut self) -> &'b str
+  {
+    self.next().ok_or_else(|| anyhow!("missing"))??
+  }
+
+  #[throws(AE)]
+  pub fn need_parse<T>(&mut self) -> T
+  where T: FromStr,
+        AE: From<T::Err>,
+  {
+    self.parse()?.ok_or_else(|| anyhow!("missing"))?
+  }
+
+  #[throws(AE)]
+  pub fn parse<T>(&mut self) -> Option<T>
+  where T: FromStr,
+        AE: From<T::Err>,
+  {
+    let s = if let Some(r) = self.next() { r? } else { return None };
+    Some(s.parse()?)
+  }
+
+  pub fn remaining_bytes_len(&self) -> usize {
+    if let Some(last) = self.last {
+      self.buf.len() - last
+    } else {
+      0
+    }
+  }
+}
+                                      
+impl<'b> Iterator for MetadataFieldIterator<'b> {
+  type Item = Result<&'b str, std::str::Utf8Error>;
+  fn next(&mut self) -> Option<Result<&'b str, std::str::Utf8Error>> {
+    let last = self.last?;
+    let (s, last) = match self.iter.next() {
+      Some(nl) => (&self.buf[last..nl], Some(nl+1)),
+      None     => (&self.buf[last..],   None),
+    };
+    self.last = last;
+    let s = str::from_utf8(s).map(|s| s.trim());
+    Some(s)
+  }
+}
+impl<'b> std::iter::FusedIterator for MetadataFieldIterator<'b> { }