jeudi 4 août 2016

Struct function which can get Any type

I have the next code which serialize basic Rust types to BERT format:

pub struct Serializer;

pub trait Serialize<T> {
    fn to_bert(&self, data: T) -> Vec<u8>;
}

impl Serializer {

    pub fn new() -> Serializer {
        Serializer{}
    }

    pub fn term_to_binary<T: Any + Debug>(&self, data: T) -> Vec<u8> {
        self.to_bert(data)
    }

    pub fn generate_term(&self, tag: BertTag, data: Vec<u8>) -> Vec<u8> {
        let mut binary = vec![tag as u8];
        binary.extend(data.iter().clone());
        binary
    }

    pub fn convert_string_to_binary(&self, data: &str) -> Vec<u8> {
        let binary_string = data.as_bytes();
        let binary_length = binary_string.len() as u8;
        let mut binary = vec![0u8, binary_length];
        binary.extend(binary_string.iter().clone());
        binary
    }

    pub fn merge_atoms(&self, atom_1: Vec<u8>, atom_2: Vec<u8>) -> Vec<u8> {
        let mut binary: Vec<u8> = atom_1.clone();
        binary.extend(atom_2.iter().clone());
        binary
    }

    pub fn get_bert_atom(&self) -> Vec<u8> {
        let binary_string = self.convert_string_to_binary(BERT_LABEL);
        self.generate_term(BertTag::Atom, binary_string)
    }
}

impl Serialize<u8> for Serializer {
    fn to_bert(&self, data: u8) -> Vec<u8> {
        self.generate_term(BertTag::SmallInteger, vec![data])
    }
}

impl Serialize<bool> for Serializer {
    fn to_bert(&self, data: bool) -> Vec<u8> {
        let boolean_string = data.to_string();
        let binary_boolean = self.convert_string_to_binary(&boolean_string);

        let bert_atom = self.get_bert_atom();
        let boolean_atom = self.generate_term(BertTag::Atom, binary_boolean);

        self.merge_atoms(bert_atom, boolean_atom)
    }
}

The main questions there is how to implement correctly in terms of Rust language term_to_binary function into which we can pass some basic types (like integers, booleans and so on). Can I somehow to get a type "on the fly" and a make a call for a specific function when term_to_binary have taken some data?

After that I want to write few test, which let me sure that all works correctly. For example it can be like that:

#[cfg(test)]
mod test {
    use super::{Serializer};

    #[test]
    fn test_serialize_bool() {
        let serializer = Serializer::new();

        println!(serializer.term_to_binary(true), [100, 0, 4, 116, 114, 117, 101])
    }
}

For an integer, maps, tuples test cases will be look pretty similar further.

Aucun commentaire:

Enregistrer un commentaire