1use core::fmt;
44
45use alloc::string::{String, ToString};
46
47use imap_codec::{
48 CommandCodec,
49 fragmentizer::Fragmentizer,
50 imap_types::{
51 command::{Command, CommandBody},
52 core::TagGenerator,
53 mailbox::Mailbox,
54 response::{StatusKind, Tagged},
55 },
56};
57use log::trace;
58use thiserror::Error;
59
60use crate::{coroutine::*, imap_try, rfc3501::mailbox::encode_inplace, send::*};
61
62#[derive(Clone, Debug, Error)]
64pub enum ImapMailboxRenameError {
65 #[error("IMAP RENAME failed: NO {0}")]
67 No(String),
68 #[error("IMAP RENAME failed: BAD {0}")]
70 Bad(String),
71 #[error("IMAP RENAME failed: BYE {0}")]
73 Bye(String),
74 #[error("IMAP RENAME failed: server did not return a tagged response")]
76 MissingTagged,
77 #[error("IMAP RENAME failed: {0}")]
79 Send(#[from] ImapSendError),
80}
81
82pub struct ImapMailboxRename {
84 state: State,
85}
86
87impl ImapMailboxRename {
88 pub fn new(mut from: Mailbox<'static>, mut to: Mailbox<'static>) -> Self {
90 encode_inplace(&mut from);
91 encode_inplace(&mut to);
92
93 let command = Command {
94 tag: TagGenerator::new().generate(),
95 body: CommandBody::Rename { from, to },
96 };
97
98 trace!("send IMAP command {command:?}");
99
100 let state = State::Send(ImapSend::new(CommandCodec::new(), command));
101
102 Self { state }
103 }
104}
105
106impl ImapCoroutine for ImapMailboxRename {
107 type Yield = ImapYield;
108 type Return = Result<(), ImapMailboxRenameError>;
109
110 fn resume(
111 &mut self,
112 fragmentizer: &mut Fragmentizer,
113 arg: Option<&[u8]>,
114 ) -> ImapCoroutineState<Self::Yield, Self::Return> {
115 match &mut self.state {
116 State::Send(send) => {
117 let out = imap_try!(send, fragmentizer, arg);
118
119 if let Some(bye) = out.bye {
120 let err = ImapMailboxRenameError::Bye(bye.text.to_string());
121 return ImapCoroutineState::Complete(Err(err));
122 }
123
124 let Some(Tagged { body, .. }) = out.tagged else {
125 let err = ImapMailboxRenameError::MissingTagged;
126 return ImapCoroutineState::Complete(Err(err));
127 };
128
129 match body.kind {
130 StatusKind::Ok => ImapCoroutineState::Complete(Ok(())),
131 StatusKind::No => {
132 let err = ImapMailboxRenameError::No(body.text.to_string());
133 ImapCoroutineState::Complete(Err(err))
134 }
135 StatusKind::Bad => {
136 let err = ImapMailboxRenameError::Bad(body.text.to_string());
137 ImapCoroutineState::Complete(Err(err))
138 }
139 }
140 }
141 }
142 }
143}
144
145enum State {
146 Send(ImapSend<CommandCodec>),
147}
148
149impl fmt::Display for State {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 match self {
152 Self::Send(_) => f.write_str("send rename"),
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use core::str;
160
161 use alloc::{borrow::ToOwned, format, vec::Vec};
162
163 use crate::rfc3501::rename::*;
164
165 #[test]
166 fn success_returns_ok() {
167 let mut rename = ImapMailboxRename::new(
168 "Old".try_into().expect("valid mailbox"),
169 "New".try_into().expect("valid mailbox"),
170 );
171 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
172
173 let bytes = expect_wants_write(&mut rename, &mut frag, None);
174 let line = str::from_utf8(&bytes).expect("utf8 command");
175 let tag = first_word(line).to_owned();
176 assert!(line.contains("RENAME Old New"));
177
178 expect_wants_read(&mut rename, &mut frag);
179
180 let reply = format!("{tag} OK RENAME completed\r\n");
181 expect_complete_ok(&mut rename, &mut frag, reply.as_bytes());
182 }
183
184 #[test]
185 fn tagged_no_returns_no_error() {
186 let mut rename = ImapMailboxRename::new(
187 "Old".try_into().expect("valid mailbox"),
188 "New".try_into().expect("valid mailbox"),
189 );
190 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
191
192 let bytes = expect_wants_write(&mut rename, &mut frag, None);
193 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
194
195 expect_wants_read(&mut rename, &mut frag);
196
197 let reply = format!("{tag} NO target mailbox already exists\r\n");
198 let err = expect_complete_err(&mut rename, &mut frag, reply.as_bytes());
199 let ImapMailboxRenameError::No(text) = err else {
200 panic!("expected ImapMailboxRenameError::No, got {err:?}");
201 };
202 assert_eq!(text, "target mailbox already exists");
203 }
204
205 #[test]
206 fn bye_returns_bye_error() {
207 let mut rename = ImapMailboxRename::new(
208 "Old".try_into().expect("valid mailbox"),
209 "New".try_into().expect("valid mailbox"),
210 );
211 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
212
213 let _ = expect_wants_write(&mut rename, &mut frag, None);
214 expect_wants_read(&mut rename, &mut frag);
215
216 let err = expect_complete_err(&mut rename, &mut frag, b"* BYE going down\r\n");
217 let ImapMailboxRenameError::Bye(text) = err else {
218 panic!("expected ImapMailboxRenameError::Bye, got {err:?}");
219 };
220 assert_eq!(text, "going down");
221 }
222
223 fn expect_wants_write(
224 cor: &mut ImapMailboxRename,
225 frag: &mut Fragmentizer,
226 arg: Option<&[u8]>,
227 ) -> Vec<u8> {
228 match cor.resume(frag, arg) {
229 ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
230 state => panic!("expected WantsWrite, got {state:?}"),
231 }
232 }
233
234 fn expect_wants_read(cor: &mut ImapMailboxRename, frag: &mut Fragmentizer) {
235 match cor.resume(frag, None) {
236 ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
237 state => panic!("expected WantsRead, got {state:?}"),
238 }
239 }
240
241 fn expect_complete_ok(cor: &mut ImapMailboxRename, frag: &mut Fragmentizer, reply: &[u8]) {
242 match cor.resume(frag, Some(reply)) {
243 ImapCoroutineState::Complete(Ok(())) => {}
244 state => panic!("expected Complete(Ok), got {state:?}"),
245 }
246 }
247
248 fn expect_complete_err(
249 cor: &mut ImapMailboxRename,
250 frag: &mut Fragmentizer,
251 reply: &[u8],
252 ) -> ImapMailboxRenameError {
253 match cor.resume(frag, Some(reply)) {
254 ImapCoroutineState::Complete(Err(err)) => err,
255 state => panic!("expected Complete(Err), got {state:?}"),
256 }
257 }
258
259 fn first_word(line: &str) -> &str {
260 line.split_whitespace()
261 .next()
262 .expect("first whitespace-separated token")
263 }
264}