qnighy / yasna.rs

ASN.1 library for Rust
Apache License 2.0
42 stars 31 forks source link

How to impl DEREncodable for CHOICE #52

Closed BruceChen1995 closed 4 years ago

BruceChen1995 commented 4 years ago

How to impl DEREncodable for a CHOICE in struct:

PrefixFulfillment ::= SEQUENCE {
     subcondition       Condition
}
Condition ::= CHOICE {
     preimageSha256   [0] SimpleSha256Condition,
     prefixSha256     [1] CompoundSha256Condition,
     thresholdSha256  [2] CompoundSha256Condition,
     rsaSha256        [3] SimpleSha256Condition,
     ed25519Sha256    [4] SimpleSha256Condition
}
use yasna;
use yasna::tags::*;
let data = &[48, 5, 2, 1, 10, 5, 0];
let asn = yasna::parse_der(data, |reader| {
    reader.collect_sequence_of(|reader| {
        let tag = try!(reader.lookahead_tag());
        let choice;
        if tag == TAG_INTEGER {
            choice = Some(try!(reader.read_i64()));
        } else {
            try!(reader.read_null());
            choice = None;
        }
        return Ok(choice);
    })
}).unwrap();
assert_eq!(&asn, &[Some(10), None]);
est31 commented 4 years ago

You can use write_tagged (or maybe the _implicit variant, depending on what is specified) to write the tag, then write the rest continuing from there.