[英]Borsh JS and Borsh Rust slightly different serialized output
我正在嘗試將 borsh 序列化數據從 JS 發送到 rust 應用程序。 但是,當序列化 javascript 和 rust 中的數據(以比較輸出)時,我在 rust 序列化 output 中得到 4 個額外字節。這是代碼:
博爾什 JS 代碼
// class
class Poll {
id: string = '';
question: string = '';
options: string[] = [];
votes: number[] = [];
constructor(fields?: {
id: string;
question: string;
options: string[];
votes: number[];
}) {
if (fields) {
this.id = fields.id;
this.question = fields.question;
this.options = fields.options;
this.votes = fields.votes;
}
}
}
// Schema
const schema: Schema = new Map([
[
Poll,
{
kind: 'struct',
fields: [
['id', 'string'],
['question', 'string'],
['options', ['string']],
['votes', ['u32', 1]],
],
},
],
]);
// class object
const testPoll = new Poll({
id: '1',
question: 'What is your favorite color?',
options: ['a', 'b', 'c'],
votes: [100],
});
//object serialization
let serializedPoll: Uint8Array = new Uint8Array();
serializedPoll = serialize(schema, testPoll); // this succeeds
// output
[1, 0, 0, 0, 49, 28, 0, 0, 0, 87, 104, 97, 116, 32, 105, 115, 32, 121, 111, 117, 114, 32, 102, 97, 118, 111, 114, 105, 116, 101, 32, 99, 111, 108, 111, 114, 63, 3, 0, 0, 0, 1, 0, 0, 0, 97, 1, 0, 0, 0, 98, 1, 0, 0, 0, 99, 100, 0, 0, 0]
博爾什 Rust 代碼
#[derive(BorshDeserialize, BorshSerialize, Debug)]
pub struct Poll {
pub id: String,
pub question: String,
pub options: Vec<String>,
pub votes: Vec<u32>,
}
// poll object - with same values as that in JS code above
let p = Poll {
id: "1".to_string(),
question: "What is your favorite color?".to_string(),
options: vec!["a".to_string(), "b".to_string(), "c".to_string()],
votes: vec![100],
};
// serialization
let serialized_data = p.try_to_vec().unwrap(); // this succeeds
//output
[1, 0, 0, 0, 49, 28, 0, 0, 0, 87, 104, 97, 116, 32, 105, 115, 32, 121, 111, 117, 114, 32, 102, 97, 118, 111, 114, 105, 116, 101, 32, 99, 111, 108, 111, 114, 63, 3, 0, 0, 0, 1, 0, 0, 0, 97, 1, 0, 0, 0, 98, 1, 0, 0, 0, 99, 1, 0, 0, 0, 100, 0, 0, 0]
比較兩者的輸出
[1, 0, 0, 0, 49, 28, 0, 0, 0, 87, 104, 97, 116, 32, 105, 115, 32, 121, 111, 117, 114, 32, 102, 97, 118, 111, 114, 105, 116, 101, 32, 99, 111, 108, 111, 114, 63, 3, 0, 0, 0, 1, 0, 0, 0, 97, 1, 0, 0, 0, 98, 1, 0, 0, 0, 99, 100, 0, 0, 0]
[1, 0, 0, 0, 49, 28, 0, 0, 0, 87, 104, 97, 116, 32, 105, 115, 32, 121, 111, 117, 114, 32, 102, 97, 118, 111, 114, 105, 116, 101, 32, 99, 111, 108, 111, 114, 63, 3, 0, 0, 0, 1, 0, 0, 0, 97, 1, 0, 0, 0, 98, 1, 0, 0, 0, 99, 1, 0, 0, 0, 100, 0, 0, 0]
序列化為 output 的 rust 中有額外的 4 個字節(1、0、0、0) 。我相信這是因為Vec<u32>
用於votes
字段(它適用於u32
)。 但是我無法理解為什么會這樣。
感謝任何形式的幫助/見解。
謝謝!
Vec<u32>
必須對數據的長度進行編碼,因為Vec
表示可變大小。 相反,您在 JS 中將模式設計為['u32', 1]
,這是一個長度為 1 的數組,因此它不需要編碼長度,因為它是固定大小。
要解決差異,請將架構設置為可變大小數組: ['u32']
。 或者將 Rust 中的類型更改為固定大小的數組: votes: [u32; 1]
votes: [u32; 1]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.