sansio_codec/string_codec/
mod.rs

1//! Handlers for converting between TaggedBytesMut and TaggedString
2
3use bytes::{BufMut, BytesMut};
4use std::time::Instant;
5
6use sansio::{Context, Handler};
7use sansio_transport::{TaggedBytesMut, TaggedString};
8
9/// A tagged StringCodec handler that reads with input of TaggedBytesMut and output of TaggedString,
10/// or writes with input of TaggedString and output of TaggedBytesMut
11pub struct TaggedStringCodec;
12
13impl Default for TaggedStringCodec {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl TaggedStringCodec {
20    /// Creates a new TaggedStringCodec handler
21    pub fn new() -> Self {
22        Self {}
23    }
24}
25
26impl Handler for TaggedStringCodec {
27    type Rin = TaggedBytesMut;
28    type Rout = TaggedString;
29    type Win = TaggedString;
30    type Wout = TaggedBytesMut;
31
32    fn name(&self) -> &str {
33        "TaggedStringCodec"
34    }
35
36    fn handle_read(
37        &mut self,
38        ctx: &Context<Self::Rin, Self::Rout, Self::Win, Self::Wout>,
39        msg: Self::Rin,
40    ) {
41        match String::from_utf8(msg.message.to_vec()) {
42            Ok(message) => {
43                ctx.fire_handle_read(TaggedString {
44                    now: msg.now,
45                    transport: msg.transport,
46                    message,
47                });
48            }
49            Err(err) => ctx.fire_handle_error(err.into()),
50        }
51    }
52
53    fn poll_write(
54        &mut self,
55        ctx: &Context<Self::Rin, Self::Rout, Self::Win, Self::Wout>,
56    ) -> Option<Self::Wout> {
57        if let Some(msg) = ctx.fire_poll_write() {
58            let mut buf = BytesMut::new();
59            buf.put(msg.message.as_bytes());
60            Some(TaggedBytesMut {
61                now: Instant::now(),
62                transport: msg.transport,
63                message: buf,
64            })
65        } else {
66            None
67        }
68    }
69}