use bytes::{BufMut, BytesMut};
use tokio_util::codec::Encoder;
use vector_config::configurable_component;
use super::BoxedFramingError;
#[configurable_component]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct CharacterDelimitedEncoderConfig {
pub character_delimited: CharacterDelimitedEncoderOptions,
}
impl CharacterDelimitedEncoderConfig {
pub const fn new(delimiter: u8) -> Self {
Self {
character_delimited: CharacterDelimitedEncoderOptions { delimiter },
}
}
pub const fn build(&self) -> CharacterDelimitedEncoder {
CharacterDelimitedEncoder::new(self.character_delimited.delimiter)
}
}
#[configurable_component]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CharacterDelimitedEncoderOptions {
#[configurable(metadata(docs::type_override = "ascii_char"))]
#[serde(with = "vector_core::serde::ascii_char")]
pub delimiter: u8,
}
#[derive(Debug, Clone)]
pub struct CharacterDelimitedEncoder {
pub delimiter: u8,
}
impl CharacterDelimitedEncoder {
pub const fn new(delimiter: u8) -> Self {
Self { delimiter }
}
}
impl Encoder<()> for CharacterDelimitedEncoder {
type Error = BoxedFramingError;
fn encode(&mut self, _: (), buffer: &mut BytesMut) -> Result<(), BoxedFramingError> {
buffer.put_u8(self.delimiter);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode() {
let mut codec = CharacterDelimitedEncoder::new(b'\n');
let mut buffer = BytesMut::from("abc");
codec.encode((), &mut buffer).unwrap();
assert_eq!(b"abc\n", &buffer[..]);
}
}