use ion_rs;
use ion_rs::IonReader;
use ion_rs::IonWriter;
use crate::core::api::API;
use crate::core::decoder_api::Decoder;
use crate::core::encoder_api::Encoder;
use crate::core::typed_api::Typed;
const DATA_TYPE: &str = "string";
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StringDTO {
value: String,
}
impl API for StringDTO {}
impl StringDTO {
pub fn new(value: &str) -> Self {
StringDTO { value: value.to_string() }
}
pub fn get_value(&self) -> &str {
&self.value
}
}
impl Typed for StringDTO {
fn get_type(&self) -> &str {
DATA_TYPE
}
fn get_data_type() -> &'static str where Self : Sized {
DATA_TYPE
}
}
impl Encoder for StringDTO {
fn encode(&self) -> Vec<u8> {
let buffer: Vec<u8> = Vec::new();
let binary_writer_builder = ion_rs::BinaryWriterBuilder::new();
let mut writer = binary_writer_builder.build(buffer.clone()).unwrap();
writer.step_in(ion_rs::IonType::Struct).expect("Error while creating an ion struct");
writer.set_field_name("value");
writer.write_string(&self.value).unwrap();
writer.step_out().unwrap();
writer.flush().unwrap();
writer.output().as_slice().to_owned()
}
}
impl Decoder for StringDTO {
fn decode(data: &[u8]) -> Self {
let mut binary_user_reader = ion_rs::ReaderBuilder::new().build(data).unwrap();
binary_user_reader.next().unwrap();
binary_user_reader.step_in().unwrap();
binary_user_reader.next().unwrap();
let value = binary_user_reader.read_string().unwrap();
StringDTO::new(value.text())
}
}
#[cfg(test)]
mod tests {
use ion_rs::IonType;
use ion_rs::IonReader;
use ion_rs::ReaderBuilder;
use ion_rs::StreamItem;
use crate::core::decoder_api::Decoder;
use crate::core::encoder_api::Encoder;
use crate::core::typed_api::Typed;
use super::StringDTO;
#[test]
fn reader_correctly_read_encoded_string() {
const STRING_VALUE: &str = "value";
let string = StringDTO::new(STRING_VALUE);
let mut binary_user_reader = ReaderBuilder::new().build(string.encode()).unwrap();
assert_eq!(StreamItem::Value(IonType::Struct), binary_user_reader.next().unwrap());
binary_user_reader.step_in().unwrap();
assert_eq!(StreamItem::Value(IonType::String), binary_user_reader.next().unwrap());
assert_eq!("value", binary_user_reader.field_name().unwrap());
assert_eq!(STRING_VALUE, binary_user_reader.read_string().unwrap().text());
binary_user_reader.step_out().unwrap();
}
#[test]
fn endec_string() {
const STRING_VALUE: &str = "value";
let string = StringDTO::new(STRING_VALUE);
assert_eq!(string, StringDTO::decode(&string.encode()));
}
#[test]
fn test_getting_data_types() {
const STRING_VALUE: &str = "value";
let string = StringDTO::new(STRING_VALUE);
assert_eq!(string.get_type(), StringDTO::get_data_type());
assert_eq!(string.get_type(), super::DATA_TYPE);
}
}