我有下一个将基本Rust类型序列化为BERT格式的代码:
// New method to handle the response
processLoginResult(response) {
console.log(response);
this.commentOnTimeOut = response;
}
submit(){
console.log(this.loginForm.value);
console.log(this.loginForm.value.email);
console.log(this.loginForm.value.password);
// Instead of calling it with email, password and the callback
// just send the added method as a callback
this.validateLogin(this.processLoginResult);
this.commentOnTimeOut = "Validating User";
console.log(this.commentOnTimeOut);
}
主要问题是如何根据Rust语言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)
}
}
函数正确实现我们可以传递一些基本类型(如整数,布尔等等)。我可以以某种方式得到一个类型&#34;在飞行中&#34;并在term_to_binary
获取某些数据时调用特定函数?
之后我想写几个测试,这让我确保一切正常。例如,它可以是这样的:
term_to_binary
对于整数,map,元组测试用例将看起来非常相似。
答案 0 :(得分:2)
查看term_to_binary
实施,您尝试拨打self.to_bert(data)
,即Serialize::to_bert(&self, data)
。为了能够进行此调用,Self
(即Serializer
)必须实施Serialize<T>
,因此我们必须将此约束添加到term_to_binary
:
pub fn term_to_binary<T>(&self, data: T) -> Vec<u8>
where Self: Serialize<T>
{
self.to_bert(data)
}
您可以添加实施T
的新序列化类型Serialize<T> for Serializer
,但可能不会更改Serializer
great。
请注意,使用Any
需要动态调度,但是对于您的示例则没有必要,因此您无需支付此费用。