2017-08-25 2 views
1

酸化ナトリウムdefines PublicKeyRust/sodiumDioxide PublicKeysにシリアル化されたときに接頭辞が付くのはなぜですか?

new_type! { 
    /// `PublicKey` for signatures 
    public PublicKey(PUBLICKEYBYTES); 
} 

The new_type macroは、に展開:

pub struct $name(pub [u8; $bytes]); 

したがって、PublicKeyは、32バイトの単純なラッパーとして定義されます。

32バイト(MyPubKey)の独自のラッパーを定義すると、bincodeは32バイトにシリアル化されます。

私がシリアル番号PublicKeyをbincodeするとき、それは40バイトです.32バイトは、その長さを含むリトルエンディアンu64で始まります。

#[macro_use] 
extern crate serde_derive; 
extern crate serde; 
extern crate bincode; 
extern crate sodiumoxide; 
use sodiumoxide::crypto::{sign, box_}; 
use bincode::{serialize, deserialize, Infinite}; 

#[derive(Serialize, Deserialize, PartialEq, Debug)] 
pub struct MyPubKey(pub [u8; 32]); 

fn main() { 
    let (pk, sk) = sign::gen_keypair(); 
    let arr: [u8; 32] = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]; 
    let mpk = MyPubKey(arr); 
    let encoded_pk: Vec<u8> = serialize(&pk, Infinite).unwrap(); 
    let encoded_arr: Vec<u8> = serialize(&arr, Infinite).unwrap(); 
    let encoded_mpk: Vec<u8> = serialize(&mpk, Infinite).unwrap(); 
    println!("encoded_pk len:{:?} {:?}", encoded_pk.len(), encoded_pk); 
    println!("encoded_arr len:{:?} {:?}", encoded_arr.len(), encoded_arr); 
    println!("encoded_mpk len:{:?} {:?}", encoded_mpk.len(), encoded_mpk); 
} 

結果:

encoded_pk len:40 [32, 0, 0, 0, 0, 0, 0, 0, 7, 199, 134, 217, 109, 46, 34, 155, 89, 232, 171, 185, 199, 190, 253, 88, 15, 202, 58, 211, 198, 49, 46, 225, 213, 233, 114, 253, 61, 182, 123, 181] 
encoded_arr len:32 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] 
encoded_mpk len:32 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] 

酸化ナトリウムのnew_type!マクロとMyPublicKeyタイプで作成PublicKey種類、違いは何ですか?

PublicKeyから32バイトを取得して効率的にシリアル化できますか?

+0

それはスライスに変換することは意図的か、彼らが代わりにシリアライズできるかどうだったかどうかを確認するために酸化ナトリウムの開発者に確認する価値があるかもしれに配列を直接。 – Shepmaster

答えて

2

implementation of the serializationまでです。酸化ナトリウムは、スライスに型を変換した後、それをシリアライズすることにより、すべてのシリアライゼーションを実装することを選択した:

#[cfg(feature = "serde")] 
impl ::serde::Serialize for $newtype { 
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 
     where S: ::serde::Serializer 
    { 
     serializer.serialize_bytes(&self[..]) 
    } 
} 

スライスがコンパイル時に知られているサイズを持っていないので、シリアライゼーションそのデシリアライズように長さを含める必要があります発生する可能性があります。

あなたはおそらく、あなた自身のserialization for a remote typeあるいは単に直接内側のフィールドをシリアル化を実装することができます

serialize(&pk.0, Infinite) 
関連する問題