Use imap_proto to parse the search responses into a HashSet of ids

This commit is contained in:
Massimiliano Torromeo 2018-10-05 18:04:03 +02:00
parent 5facd16e0e
commit 11e666ea91
No known key found for this signature in database
GPG key ID: 11675C743429DDEF
2 changed files with 44 additions and 31 deletions

View file

@ -5,11 +5,12 @@ use std::io::{self, Read, Write};
use std::net::{TcpStream, ToSocketAddrs}; use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration; use std::time::Duration;
use std::ops::{Deref,DerefMut}; use std::ops::{Deref,DerefMut};
use std::collections::HashSet;
use super::authenticator::Authenticator; use super::authenticator::Authenticator;
use super::error::{Error, ParseError, Result, ValidateError}; use super::error::{Error, ParseError, Result, ValidateError};
use super::parse::{ use super::parse::{
parse_authenticate_response, parse_capabilities, parse_fetches, parse_mailbox, parse_names, parse_search_ids, parse_authenticate_response, parse_capabilities, parse_fetches, parse_mailbox, parse_names, parse_ids,
}; };
use super::types::*; use super::types::*;
@ -622,17 +623,17 @@ impl <T: Read + Write> Session<T> {
/// Searches the mailbox for messages that match the given criteria and returns /// Searches the mailbox for messages that match the given criteria and returns
/// the list of message sequence numbers of those messages. /// the list of message sequence numbers of those messages.
pub fn search(&mut self, query: &str) -> Result<Vec<u32>> { pub fn search(&mut self, query: &str) -> ZeroCopyResult<HashSet<u32>> {
self.run_command_and_read_response(&format!("SEARCH {}", query)) self.run_command_and_read_response(&format!("SEARCH {}", query))
.and_then(|lines| parse_search_ids(&lines[..])) .and_then(parse_ids)
} }
/// Searches the mailbox for messages that match the given criteria and returns /// Searches the mailbox for messages that match the given criteria and returns
/// the list of unique identifier numbers of those messages. /// the list of unique identifier numbers of those messages.
pub fn uid_search(&mut self, query: &str) -> Result<Vec<u32>> { pub fn uid_search(&mut self, query: &str) -> ZeroCopyResult<HashSet<u32>> {
eprint!("{}", format!("UID SEARCH {}", query)); eprint!("{}", format!("UID SEARCH {}", query));
self.run_command_and_read_response(&format!("UID SEARCH {}", query)) self.run_command_and_read_response(&format!("UID SEARCH {}", query))
.and_then(|lines| parse_search_ids(&lines[..])) .and_then(parse_ids)
} }
// these are only here because they are public interface, the rest is in `Connection` // these are only here because they are public interface, the rest is in `Connection`
@ -1079,11 +1080,12 @@ mod tests {
let mock_stream = MockStream::new(response); let mock_stream = MockStream::new(response);
let mut session = mock_session!(mock_stream); let mut session = mock_session!(mock_stream);
let ids = session.search("Unseen").unwrap(); let ids = session.search("Unseen").unwrap();
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert!( assert!(
session.stream.get_ref().written_buf == b"a1 SEARCH Unseen\r\n".to_vec(), session.stream.get_ref().written_buf == b"a1 SEARCH Unseen\r\n".to_vec(),
"Invalid search command" "Invalid search command"
); );
assert_eq!(ids, vec![1, 2, 3, 4, 5]); assert_eq!(ids, [1, 2, 3, 4, 5].iter().cloned().collect());
} }
#[test] #[test]
@ -1094,11 +1096,12 @@ mod tests {
let mock_stream = MockStream::new(response); let mock_stream = MockStream::new(response);
let mut session = mock_session!(mock_stream); let mut session = mock_session!(mock_stream);
let ids = session.uid_search("Unseen").unwrap(); let ids = session.uid_search("Unseen").unwrap();
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert!( assert!(
session.stream.get_ref().written_buf == b"a1 UID SEARCH Unseen\r\n".to_vec(), session.stream.get_ref().written_buf == b"a1 UID SEARCH Unseen\r\n".to_vec(),
"Invalid search command" "Invalid search command"
); );
assert_eq!(ids, vec![1, 2, 3, 4, 5]); assert_eq!(ids, [1, 2, 3, 4, 5].iter().cloned().collect());
} }
#[test] #[test]

View file

@ -1,7 +1,7 @@
use imap_proto::{self, MailboxDatum, Response}; use imap_proto::{self, MailboxDatum, Response};
use nom::IResult; use nom::IResult;
use regex::Regex; use regex::Regex;
use std::str; use std::collections::HashSet;
use super::error::{Error, ParseError, Result}; use super::error::{Error, ParseError, Result};
use super::types::*; use super::types::*;
@ -129,7 +129,6 @@ pub fn parse_fetches(lines: Vec<u8>) -> ZeroCopyResult<Vec<Fetch>> {
pub fn parse_capabilities(lines: Vec<u8>) -> ZeroCopyResult<Capabilities> { pub fn parse_capabilities(lines: Vec<u8>) -> ZeroCopyResult<Capabilities> {
let f = |mut lines| { let f = |mut lines| {
use std::collections::HashSet;
let mut caps = HashSet::new(); let mut caps = HashSet::new();
loop { loop {
match imap_proto::parse_response(lines) { match imap_proto::parse_response(lines) {
@ -223,24 +222,30 @@ pub fn parse_mailbox(mut lines: &[u8]) -> Result<Mailbox> {
} }
} }
pub fn parse_search_ids(lines: &[u8]) -> Result<Vec<u32>> { pub fn parse_ids(lines: Vec<u8>) -> ZeroCopyResult<HashSet<u32>> {
match str::from_utf8(lines) { let f = |mut lines| {
Ok(resp) => { let mut ids = HashSet::new();
let re = Regex::new(r"^(?i)\* SEARCH((?:\s+[0-9]+)*)\s*$").unwrap(); loop {
match re.captures(resp) { match imap_proto::parse_response(lines) {
Some(cap) => { IResult::Done(rest, Response::IDs(c)) => {
let mut line = cap.get(1).map(|m| m.as_str()).unwrap_or(""); lines = rest;
Ok(line ids.extend(c);
.trim()
.split(' ') if lines.is_empty() {
.filter_map(|id| id.trim().parse().ok()) break Ok(ids);
.collect())
}
None => Err(Error::Parse(ParseError::Invalid(lines.to_vec()))),
} }
} }
Err(_) => Err(Error::Parse(ParseError::Invalid(lines.to_vec()))), IResult::Done(_, resp) => {
break Err(resp.into());
} }
_ => {
break Err(Error::Parse(ParseError::Invalid(lines.to_vec())));
}
}
}
};
unsafe { ZeroCopy::new(lines, f) }
} }
#[cfg(test)] #[cfg(test)]
@ -312,11 +317,14 @@ mod tests {
} }
#[test] #[test]
fn parse_search_ids_test() { fn parse_ids_test() {
let lines = "* SEARCH 1600 1698 1739 1781 1795 1885 1891 1892 1893 1898 1899 1901 1911 1926 1932 1933 1993 1994 2007 2032 2033 2041 2053 2062 2063 2065 2066 2072 2078 2079 2082 2084 2095 2100 2101 2102 2103 2104 2107 2116 2120 2135 2138 2154 2163 2168 2172 2189 2193 2198 2199 2205 2212 2213 2221 2227 2267 2275 2276 2295 2300 2328 2330 2332 2333 2334 2335 2336 2337 2338 2339 2341 2342 2347 2349 2350 2358 2359 2362 2369 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2390 2392 2397 2400 2401 2403 2405 2409 2411 2414 2417 2419 2420 2424 2426 2428 2439 2454 2456 2467 2468 2469 2490 2515 2519 2520 2521".as_bytes(); let lines = b"* SEARCH 1600 1698 1739 1781 1795 1885 1891 1892 1893 1898 1899 1901 1911 1926 1932 1933 1993 1994 2007 2032 2033 2041 2053 2062 2063 2065 2066 2072 2078 2079 2082 2084 2095 2100 2101 2102 2103 2104 2107 2116 2120 2135 2138 2154 2163 2168 2172 2189 2193 2198 2199 2205 2212 2213 2221 2227 2267 2275 2276 2295 2300 2328 2330 2332 2333 2334\r\n\
* SEARCH 2335 2336 2337 2338 2339 2341 2342 2347 2349 2350 2358 2359 2362 2369 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2390 2392 2397 2400 2401 2403 2405 2409 2411 2414 2417 2419 2420 2424 2426 2428 2439 2454 2456 2467 2468 2469 2490 2515 2519 2520 2521\r\n";
let ids = parse_ids(lines.to_vec()).unwrap();
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert_eq!( assert_eq!(
parse_search_ids(lines).unwrap(), ids,
vec![ [
1600, 1698, 1739, 1781, 1795, 1885, 1891, 1892, 1893, 1898, 1899, 1901, 1911, 1926, 1600, 1698, 1739, 1781, 1795, 1885, 1891, 1892, 1893, 1898, 1899, 1901, 1911, 1926,
1932, 1933, 1993, 1994, 2007, 2032, 2033, 2041, 2053, 2062, 2063, 2065, 2066, 2072, 1932, 1933, 1993, 1994, 2007, 2032, 2033, 2041, 2053, 2062, 2063, 2065, 2066, 2072,
2078, 2079, 2082, 2084, 2095, 2100, 2101, 2102, 2103, 2104, 2107, 2116, 2120, 2135, 2078, 2079, 2082, 2084, 2095, 2100, 2101, 2102, 2103, 2104, 2107, 2116, 2120, 2135,
@ -326,10 +334,12 @@ mod tests {
2375, 2376, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2390, 2392, 2375, 2376, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2390, 2392,
2397, 2400, 2401, 2403, 2405, 2409, 2411, 2414, 2417, 2419, 2420, 2424, 2426, 2428, 2397, 2400, 2401, 2403, 2405, 2409, 2411, 2414, 2417, 2419, 2420, 2424, 2426, 2428,
2439, 2454, 2456, 2467, 2468, 2469, 2490, 2515, 2519, 2520, 2521 2439, 2454, 2456, 2467, 2468, 2469, 2490, 2515, 2519, 2520, 2521
] ].iter().cloned().collect()
); );
let lines = "* SEARCH".as_bytes(); let lines = b"* SEARCH\r\n";
assert_eq!(parse_search_ids(lines).unwrap(), Vec::<u32>::new()); let ids = parse_ids(lines.to_vec()).unwrap();
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert_eq!(ids, HashSet::<u32>::new());
} }
} }