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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! ASN.1 `TeletexString` support.
//!
use crate::{asn1::AnyRef, FixedTag, Result, StrRef, Tag};
use core::{fmt, ops::Deref};

macro_rules! impl_teletex_string {
    ($type: ty) => {
        impl_teletex_string!($type,);
    };
    ($type: ty, $($li: lifetime)?) => {
        impl_string_type!($type, $($li),*);

        impl<$($li),*> FixedTag for $type {
            const TAG: Tag = Tag::TeletexString;
        }

        impl<$($li),*> fmt::Debug for $type {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "TeletexString({:?})", self.as_str())
            }
        }
    };
}

/// ASN.1 `TeletexString` type.
///
/// Supports a subset the ASCII character set (described below).
///
/// For UTF-8, use [`Utf8StringRef`][`crate::asn1::Utf8StringRef`] instead.
/// For the full ASCII character set, use
/// [`Ia5StringRef`][`crate::asn1::Ia5StringRef`].
///
/// This is a zero-copy reference type which borrows from the input data.
///
/// # Supported characters
///
/// The standard defines a complex character set allowed in this type. However, quoting the ASN.1
/// mailing list, "a sizable volume of software in the world treats TeletexString (T61String) as a
/// simple 8-bit string with mostly Windows Latin 1 (superset of iso-8859-1) encoding".
///
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
pub struct TeletexStringRef<'a> {
    /// Inner value
    inner: StrRef<'a>,
}

impl<'a> TeletexStringRef<'a> {
    /// Create a new ASN.1 `TeletexString`.
    pub fn new<T>(input: &'a T) -> Result<Self>
    where
        T: AsRef<[u8]> + ?Sized,
    {
        let input = input.as_ref();

        // FIXME: support higher part of the charset
        if input.iter().any(|&c| c > 0x7F) {
            return Err(Self::TAG.value_error());
        }

        StrRef::from_bytes(input)
            .map(|inner| Self { inner })
            .map_err(|_| Self::TAG.value_error())
    }
}

impl_teletex_string!(TeletexStringRef<'a>, 'a);

impl<'a> Deref for TeletexStringRef<'a> {
    type Target = StrRef<'a>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a> From<&TeletexStringRef<'a>> for TeletexStringRef<'a> {
    fn from(value: &TeletexStringRef<'a>) -> TeletexStringRef<'a> {
        *value
    }
}

impl<'a> From<TeletexStringRef<'a>> for AnyRef<'a> {
    fn from(teletex_string: TeletexStringRef<'a>) -> AnyRef<'a> {
        AnyRef::from_tag_and_value(Tag::TeletexString, teletex_string.inner.into())
    }
}

#[cfg(feature = "alloc")]
pub use self::allocation::TeletexString;

#[cfg(feature = "alloc")]
mod allocation {
    use super::TeletexStringRef;

    use crate::{
        asn1::AnyRef,
        referenced::{OwnedToRef, RefToOwned},
        BytesRef, Error, FixedTag, Result, StrOwned, Tag,
    };
    use alloc::string::String;
    use core::{fmt, ops::Deref};

    /// ASN.1 `TeletexString` type.
    ///
    /// Supports a subset the ASCII character set (described below).
    ///
    /// For UTF-8, use [`Utf8StringRef`][`crate::asn1::Utf8StringRef`] instead.
    /// For the full ASCII character set, use
    /// [`Ia5StringRef`][`crate::asn1::Ia5StringRef`].
    ///
    /// # Supported characters
    ///
    /// The standard defines a complex character set allowed in this type. However, quoting the ASN.1
    /// mailing list, "a sizable volume of software in the world treats TeletexString (T61String) as a
    /// simple 8-bit string with mostly Windows Latin 1 (superset of iso-8859-1) encoding".
    ///
    #[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
    pub struct TeletexString {
        /// Inner value
        inner: StrOwned,
    }

    impl TeletexString {
        /// Create a new ASN.1 `TeletexString`.
        pub fn new<T>(input: &T) -> Result<Self>
        where
            T: AsRef<[u8]> + ?Sized,
        {
            let input = input.as_ref();

            TeletexStringRef::new(input)?;

            StrOwned::from_bytes(input)
                .map(|inner| Self { inner })
                .map_err(|_| Self::TAG.value_error())
        }
    }

    impl_teletex_string!(TeletexString);

    impl Deref for TeletexString {
        type Target = StrOwned;

        fn deref(&self) -> &Self::Target {
            &self.inner
        }
    }

    impl<'a> From<TeletexStringRef<'a>> for TeletexString {
        fn from(value: TeletexStringRef<'a>) -> TeletexString {
            let inner =
                StrOwned::from_bytes(value.inner.as_bytes()).expect("Invalid TeletexString");
            Self { inner }
        }
    }

    impl<'a> From<&'a TeletexString> for AnyRef<'a> {
        fn from(teletex_string: &'a TeletexString) -> AnyRef<'a> {
            AnyRef::from_tag_and_value(
                Tag::TeletexString,
                BytesRef::new(teletex_string.inner.as_bytes()).expect("Invalid TeletexString"),
            )
        }
    }

    impl<'a> RefToOwned<'a> for TeletexStringRef<'a> {
        type Owned = TeletexString;
        fn ref_to_owned(&self) -> Self::Owned {
            TeletexString {
                inner: self.inner.ref_to_owned(),
            }
        }
    }

    impl OwnedToRef for TeletexString {
        type Borrowed<'a> = TeletexStringRef<'a>;
        fn owned_to_ref(&self) -> Self::Borrowed<'_> {
            TeletexStringRef {
                inner: self.inner.owned_to_ref(),
            }
        }
    }

    impl TryFrom<String> for TeletexString {
        type Error = Error;

        fn try_from(input: String) -> Result<Self> {
            TeletexStringRef::new(&input)?;

            StrOwned::new(input)
                .map(|inner| Self { inner })
                .map_err(|_| Self::TAG.value_error())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::TeletexStringRef;
    use crate::Decode;
    use crate::SliceWriter;

    #[test]
    fn parse_bytes() {
        let example_bytes = &[
            0x14, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x20, 0x55, 0x73, 0x65, 0x72, 0x20, 0x31,
        ];

        let teletex_string = TeletexStringRef::from_der(example_bytes).unwrap();
        assert_eq!(teletex_string.as_str(), "Test User 1");
        let mut out = [0_u8; 30];
        let mut writer = SliceWriter::new(&mut out);
        writer.encode(&teletex_string).unwrap();
        let encoded = writer.finish().unwrap();
        assert_eq!(encoded, example_bytes);
    }
}