|
| 1 | +use imap_codec::{fragmentizer::Fragmentizer, GreetingCodec, ResponseCodec}; |
| 2 | + |
| 3 | +#[path = "common/common.rs"] |
| 4 | +mod common; |
| 5 | + |
| 6 | +use common::read_more; |
| 7 | + |
| 8 | +use crate::common::Role; |
| 9 | + |
| 10 | +enum State { |
| 11 | + Greeting, |
| 12 | + Response, |
| 13 | +} |
| 14 | + |
| 15 | +const WELCOME: &str = r#"# Parsing of IMAP greeting and responses |
| 16 | +
|
| 17 | +"S:" denotes the server. |
| 18 | +".." denotes the continuation of an (incomplete) response, e.g., due to the use of an IMAP literal. |
| 19 | +
|
| 20 | +Note: "\n" will be automatically replaced by "\r\n". |
| 21 | +
|
| 22 | +-------------------------------------------------------------------------------------------------- |
| 23 | +
|
| 24 | +Enter intial IMAP greeting followed by IMAP responses (or "exit"). |
| 25 | +"#; |
| 26 | + |
| 27 | +fn main() { |
| 28 | + println!("{}", WELCOME); |
| 29 | + |
| 30 | + let mut fragmentizer = Fragmentizer::new(10 * 1024); |
| 31 | + let mut state = State::Greeting; |
| 32 | + |
| 33 | + loop { |
| 34 | + // Progress next fragment. |
| 35 | + let Some(_fragment_info) = fragmentizer.progress() else { |
| 36 | + // Read more bytes ... |
| 37 | + let bytes = read_more(Role::Server, fragmentizer.message_bytes().is_empty()); |
| 38 | + |
| 39 | + // ... and pass the bytes to the Fragmentizer ... |
| 40 | + fragmentizer.enqueue_bytes(&bytes); |
| 41 | + |
| 42 | + // ... and try again. |
| 43 | + continue; |
| 44 | + }; |
| 45 | + |
| 46 | + // Check whether the Fragmentizer detected a complete message. |
| 47 | + if !fragmentizer.is_message_complete() { |
| 48 | + // Read next fragment. |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + // The Fragmentizer detected a complete message. |
| 53 | + match state { |
| 54 | + State::Greeting => { |
| 55 | + match fragmentizer.decode_message(&GreetingCodec::default()) { |
| 56 | + Ok(greeting) => { |
| 57 | + // Do something with the greeting ... |
| 58 | + println!("{:#?}", greeting); |
| 59 | + |
| 60 | + // ... and proceed with reponses. |
| 61 | + state = State::Response; |
| 62 | + } |
| 63 | + Err(err) => { |
| 64 | + println!("Error parsing greeting: {err:?}"); |
| 65 | + } |
| 66 | + }; |
| 67 | + } |
| 68 | + State::Response => { |
| 69 | + match fragmentizer.decode_message(&ResponseCodec::default()) { |
| 70 | + Ok(response) => { |
| 71 | + // Do something with the response. |
| 72 | + println!("{:#?}", response); |
| 73 | + } |
| 74 | + Err(err) => { |
| 75 | + println!("Error parsing response: {err:?}"); |
| 76 | + } |
| 77 | + }; |
| 78 | + } |
| 79 | + }; |
| 80 | + } |
| 81 | +} |
0 commit comments