async_imap/extensions/
id.rs1use async_channel as channel;
4use futures::io;
5use futures::prelude::*;
6use imap_proto::{self, RequestId, Response};
7use std::collections::HashMap;
8
9use crate::types::ResponseData;
10use crate::types::*;
11use crate::{
12 error::Result,
13 parse::{filter, handle_unilateral},
14};
15
16fn escape(s: &str) -> String {
17 s.replace('\\', r"\\").replace('\"', "\\\"")
18}
19
20pub(crate) fn format_identification<'a, 'b>(
24 id: impl IntoIterator<Item = (&'a str, Option<&'b str>)>,
25) -> String {
26 id.into_iter()
27 .map(|(k, v)| {
28 format!(
29 "\"{}\" {}",
30 escape(k),
31 v.map_or("NIL".to_string(), |v| format!("\"{}\"", escape(v)))
32 )
33 })
34 .collect::<Vec<String>>()
35 .join(" ")
36}
37
38pub(crate) async fn parse_id<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
39 stream: &mut T,
40 unsolicited: channel::Sender<UnsolicitedResponse>,
41 command_tag: RequestId,
42) -> Result<Option<HashMap<String, String>>> {
43 let mut id = None;
44 while let Some(resp) = stream
45 .take_while(|res| filter(res, &command_tag))
46 .try_next()
47 .await?
48 {
49 match resp.parsed() {
50 Response::Id(res) => {
51 id = res.as_ref().map(|m| {
52 m.iter()
53 .map(|(k, v)| (k.to_string(), v.to_string()))
54 .collect()
55 })
56 }
57 _ => {
58 handle_unilateral(resp, unsolicited.clone());
59 }
60 }
61 }
62
63 Ok(id)
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn test_format_identification() {
72 assert_eq!(
73 format_identification([("name", Some("MyClient"))]),
74 r#""name" "MyClient""#
75 );
76
77 assert_eq!(
78 format_identification([("name", Some(r#""MyClient"\"#))]),
79 r#""name" "\"MyClient\"\\""#
80 );
81
82 assert_eq!(
83 format_identification([("name", Some("MyClient")), ("version", Some("2.0"))]),
84 r#""name" "MyClient" "version" "2.0""#
85 );
86
87 assert_eq!(
88 format_identification([("name", None), ("version", Some("2.0"))]),
89 r#""name" NIL "version" "2.0""#
90 );
91 }
92}