passes/pass/
barcode.rs

1use serde::{Deserialize, Serialize};
2
3/// Represents a barcode on a pass.
4#[derive(Serialize, Deserialize, Debug)]
5#[serde(rename_all = "camelCase")]
6pub struct Barcode {
7    /// (Required) The message or payload to display as a barcode.
8    pub message: String,
9
10    /// (Required) The format of the barcode.
11    ///
12    /// The barcode format PKBarcodeFormatCode128 isn’t supported for watchOS.
13    pub format: BarcodeFormat,
14
15    /// The text to display near the barcode.
16    ///
17    /// For example, a human-readable version of the barcode data in case the barcode doesn’t scan.
18    #[serde(default)]
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub alt_text: Option<String>,
21
22    /// (Required) The IANA character set name of the text encoding to use to convert message from a string representation to a data representation that the system renders as a barcode.
23    pub message_encoding: String,
24}
25
26impl Default for Barcode {
27    /// Creates an empty `Barcode` with QR.
28    fn default() -> Self {
29        Self {
30            message: String::new(),
31            format: BarcodeFormat::QR,
32            alt_text: None,
33            message_encoding: String::from("iso-8859-1"),
34        }
35    }
36}
37
38/// Barcode format
39#[derive(Serialize, Deserialize, Debug)]
40pub enum BarcodeFormat {
41    /// QR - <https://en.wikipedia.org/wiki/QR_code>
42    #[serde(rename = "PKBarcodeFormatQR")]
43    QR,
44
45    /// PDF417 - <https://en.wikipedia.org/wiki/PDF417>
46    #[serde(rename = "PKBarcodeFormatPDF417")]
47    PDF417,
48
49    /// Aztec - <https://en.wikipedia.org/wiki/Aztec_Code>
50    #[serde(rename = "PKBarcodeFormatAztec")]
51    Aztec,
52
53    /// Code128 - <https://en.wikipedia.org/wiki/Code_128>
54    #[serde(rename = "PKBarcodeFormatCode128")]
55    Code128,
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn make_barcode() {
64        // Serialization test
65        let barcode = Barcode {
66            message: String::from("Hello world!"),
67            format: BarcodeFormat::PDF417,
68            ..Default::default()
69        };
70
71        let json = serde_json::to_string_pretty(&barcode).unwrap();
72
73        println!("{}", json);
74
75        let json_expected = r#"{
76  "message": "Hello world!",
77  "format": "PKBarcodeFormatPDF417",
78  "messageEncoding": "iso-8859-1"
79}"#;
80
81        assert_eq!(json_expected, json);
82
83        // Deserialization test
84        let barcode: Barcode = serde_json::from_str(json_expected).unwrap();
85        let json = serde_json::to_string_pretty(&barcode).unwrap();
86        assert_eq!(json_expected, json);
87    }
88}