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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use xdr_codec::{Pack, Write, Result, pack_opaque_array};
use ::strkey::StrKey;
use ::xdr::ToXdr;
use ::asset::Asset;

fn pack_credit<W: Write>(code: &str, issuer: &StrKey, out: &mut W) -> Result<usize> {
    let (tag, buf_len) = if code.len() <= 4 { (1, 4) } else { (2, 12) };
    Ok(tag.pack(out)? + pack_opaque_array(&code.as_bytes(), buf_len, out)? + issuer.pack(out)?)
}

impl<W: Write> Pack<W> for Asset {
    fn pack(&self, out: &mut W) -> Result<usize> {
        match *self {
            Asset::Native => 0.pack(out),
            Asset::Credit { ref code, ref issuer } => pack_credit(&code, &issuer, out),
        }
    }
}

impl ToXdr for Asset {
    fn to_writer<W: Write>(&self, mut buf: W) -> ::error::Result<usize> {
        let r = self.pack(&mut buf)?;
        Ok(r)
    }
}


#[cfg(test)]
mod tests {
    use ::xdr::ToXdr;
    use StrKey;
    use Asset;

    #[test]
    fn test_native() {
        let native = Asset::native();
        assert_eq!(native.to_base64().unwrap(), "AAAAAA==");
    }

    #[test]
    fn test_credit() {
        let issuer =
            StrKey::from_account_id("GCLDNMHZTEY6PUYQBYOVERBBZ2W3RLMYOSZWHAMY5R4YW2N6MM4LFA72")
                .unwrap();
        let test_cases = [("A", "AAAAAUEAAAAAAAAAljaw+Zkx59MQDh1SRCHOrbitmHSzY4GY7HmLab5jOLI="),
                          ("ABCD", "AAAAAUFCQ0QAAAAAljaw+Zkx59MQDh1SRCHOrbitmHSzY4GY7HmLab5jOLI="),
                          ("ABCDE",
                           "AAAAAkFCQ0RFAAAAAAAAAAAAAACWNrD5mTHn0xAOHVJEIc6tuK2YdLNjgZjseYtpvmM4sg=="),
                          ("ABCDEFGHIJKL",
                           "AAAAAkFCQ0RFRkdISUpLTAAAAACWNrD5mTHn0xAOHVJEIc6tuK2YdLNjgZjseYtpvmM4sg==")];
        for &(code, expected) in test_cases.iter() {
            let asset = Asset::credit(code.to_string(), issuer.clone()).unwrap();
            assert_eq!(asset.to_base64().unwrap(), expected);
        }

    }
}