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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use crate::Value;
use num_complex as numc;
use std::error::Error;
use std::fmt;
use std::io;

/// Error formatting a Python literal.
#[derive(Debug)]
pub enum FormatError {
    /// An error caused by the writer.
    Io(io::Error),
    /// The literal contained an empty set.
    ///
    /// There is no literal representation of an empty set in Python. (`{}`
    /// represents an empty `dict`.)
    EmptySet,
}

impl Error for FormatError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        use FormatError::*;
        match self {
            Io(err) => Some(err),
            EmptySet => None,
        }
    }
}

impl fmt::Display for FormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use FormatError::*;
        match self {
            Io(err) => write!(f, "I/O error: {}", err),
            EmptySet => write!(f, "unable to format empty set literal"),
        }
    }
}

impl From<io::Error> for FormatError {
    fn from(err: io::Error) -> FormatError {
        FormatError::Io(err)
    }
}

impl Value {
    /// Formats the value as an ASCII string.
    pub fn format_ascii(&self) -> Result<String, FormatError> {
        let mut out = Vec::new();
        self.write_ascii(&mut out)?;
        assert!(out.is_ascii());
        Ok(unsafe { String::from_utf8_unchecked(out) })
    }

    /// Writes the value as ASCII.
    ///
    /// This implementation performs a lot of small writes. If individual
    /// writes are expensive (e.g. if the writer is a [`TcpStream`]), it would
    /// be a good idea to wrap the writer in a [`BufWriter`] before passing it
    /// to `.write_ascii()`.
    ///
    /// [`TcpStream`]: https://doc.rust-lang.org/std/net/struct.TcpStream.html
    /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
    pub fn write_ascii<W: io::Write>(&self, w: &mut W) -> Result<(), FormatError> {
        match *self {
            Value::String(ref s) => {
                w.write_all(b"'")?;
                for c in s.chars() {
                    match c {
                        '\\' => w.write_all(br"\\")?,
                        '\r' => w.write_all(br"\r")?,
                        '\n' => w.write_all(br"\n")?,
                        '\'' => w.write_all(br"\'")?,
                        c if c.is_ascii() => w.write_all(&[c as u8])?,
                        c => match c as u32 {
                            n @ 0..=0xff => write!(w, r"\x{:0>2x}", n)?,
                            n @ 0..=0xffff => write!(w, r"\u{:0>4x}", n)?,
                            n @ 0..=0xffff_ffff => write!(w, r"\U{:0>8x}", n)?,
                        },
                    }
                }
                w.write_all(b"'")?;
            }
            Value::Bytes(ref bytes) => {
                w.write_all(b"b'")?;
                for byte in bytes {
                    match *byte {
                        b'\\' => w.write_all(br"\\")?,
                        b'\r' => w.write_all(br"\r")?,
                        b'\n' => w.write_all(br"\n")?,
                        b'\'' => w.write_all(br"\'")?,
                        b if b.is_ascii() => w.write_all(&[b])?,
                        b => write!(w, r"\x{:0>2x}", b)?,
                    }
                }
                w.write_all(b"'")?;
            }
            Value::Integer(ref int) => write!(w, "{}", int)?,
            Value::Float(float) => {
                // Use scientific notation to make this unambiguously a float.
                write!(w, "{:e}", float)?;
            }
            Value::Complex(numc::Complex { re, im }) => {
                write!(w, "{}{:+}j", re, im)?;
            }
            Value::Tuple(ref tup) => {
                w.write_all(b"(")?;
                match tup.len() {
                    0 => (),
                    1 => {
                        tup[0].write_ascii(w)?;
                        w.write_all(b",")?;
                    }
                    _ => {
                        tup[0].write_ascii(w)?;
                        for value in &tup[1..] {
                            w.write_all(b", ")?;
                            value.write_ascii(w)?;
                        }
                    }
                }
                w.write_all(b")")?;
            }
            Value::List(ref list) => {
                w.write_all(b"[")?;
                if !list.is_empty() {
                    list[0].write_ascii(w)?;
                    for value in &list[1..] {
                        w.write_all(b", ")?;
                        value.write_ascii(w)?;
                    }
                }
                w.write_all(b"]")?;
            }
            Value::Dict(ref dict) => {
                w.write_all(b"{")?;
                if !dict.is_empty() {
                    dict[0].0.write_ascii(w)?;
                    w.write_all(b": ")?;
                    dict[0].1.write_ascii(w)?;
                    for elem in &dict[1..] {
                        w.write_all(b", ")?;
                        elem.0.write_ascii(w)?;
                        w.write_all(b": ")?;
                        elem.1.write_ascii(w)?;
                    }
                }
                w.write_all(b"}")?;
            }
            Value::Set(ref set) => {
                if set.is_empty() {
                    return Err(FormatError::EmptySet);
                } else {
                    w.write_all(b"{")?;
                    set[0].write_ascii(w)?;
                    for value in &set[1..] {
                        w.write_all(b", ")?;
                        value.write_ascii(w)?;
                    }
                    w.write_all(b"}")?;
                }
            }
            Value::Boolean(b) => {
                if b {
                    w.write_all(b"True")?;
                } else {
                    w.write_all(b"False")?;
                }
            }
            Value::None => w.write_all(b"None")?,
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn format_string() {
        let value = Value::String("hello\th\x03\u{ff}o\x1bware\x07'y\u{1234}o\u{31234}u".into());
        let formatted = format!("{}", value);
        assert_eq!(
            formatted,
            "'hello\th\x03\\xffo\x1bware\x07\\'y\\u1234o\\U00031234u'"
        )
    }

    #[test]
    fn format_bytes() {
        let value = Value::Bytes(b"hello\th\x03\xffo\x1bware\x07'you"[..].into());
        let formatted = format!("{}", value);
        assert_eq!(formatted, "b'hello\th\x03\\xffo\x1bware\x07\\'you'")
    }

    #[test]
    fn format_complex() {
        use self::Value::*;
        assert_eq!("1+3j", format!("{}", Complex(numc::Complex::new(1., 3.))));
        assert_eq!("1-3j", format!("{}", Complex(numc::Complex::new(1., -3.))));
        assert_eq!("-1+3j", format!("{}", Complex(numc::Complex::new(-1., 3.))));
        assert_eq!(
            "-1-3j",
            format!("{}", Complex(numc::Complex::new(-1., -3.)))
        );
    }

    #[test]
    fn format_tuple() {
        use self::Value::*;
        assert_eq!("()", format!("{}", Tuple(vec![])));
        assert_eq!("(1,)", format!("{}", Tuple(vec![Integer(1.into())])));
        assert_eq!(
            "(1, 2)",
            format!("{}", Tuple(vec![Integer(1.into()), Integer(2.into())]))
        );
        assert_eq!(
            "(1, 2, 'hi')",
            format!(
                "{}",
                Tuple(vec![
                    Integer(1.into()),
                    Integer(2.into()),
                    String("hi".into()),
                ])
            ),
        );
    }

    #[test]
    fn format_list() {
        use self::Value::*;
        assert_eq!("[]", format!("{}", List(vec![])));
        assert_eq!("[1]", format!("{}", List(vec![Integer(1.into())])));
        assert_eq!(
            "[1, 2]",
            format!("{}", List(vec![Integer(1.into()), Integer(2.into())]))
        );
        assert_eq!(
            "[1, 2, 'hi']",
            format!(
                "{}",
                List(vec![
                    Integer(1.into()),
                    Integer(2.into()),
                    String("hi".into()),
                ])
            ),
        );
    }

    #[test]
    fn format_dict() {
        use self::Value::*;
        assert_eq!("{}", format!("{}", Dict(vec![])));
        assert_eq!(
            "{1: 2}",
            format!("{}", Dict(vec![(Integer(1.into()), Integer(2.into()))]))
        );
        assert_eq!(
            "{1: 2, 'foo': 'bar'}",
            format!(
                "{}",
                Dict(vec![
                    (Integer(1.into()), Integer(2.into())),
                    (String("foo".into()), String("bar".into())),
                ])
            ),
        );
    }

    #[test]
    #[should_panic]
    fn format_empty_set() {
        use self::Value::*;
        format!("{}", Set(vec![]));
    }

    #[test]
    fn format_set() {
        use self::Value::*;
        assert_eq!("{1}", format!("{}", Set(vec![Integer(1.into())])));
        assert_eq!(
            "{1, 2}",
            format!("{}", Set(vec![Integer(1.into()), Integer(2.into())]))
        );
        assert_eq!(
            "{1, 2, 'hi'}",
            format!(
                "{}",
                Set(vec![
                    Integer(1.into()),
                    Integer(2.into()),
                    String("hi".into()),
                ])
            ),
        );
    }

    #[test]
    fn format_nested() {
        use self::Value::*;
        assert_eq!(
            "{'foo': [1, True], {2+3j}: 4}",
            format!(
                "{}",
                Dict(vec![
                    (
                        String("foo".into()),
                        List(vec![Integer(1.into()), Boolean(true)]),
                    ),
                    (
                        Set(vec![Complex(numc::Complex::new(2., 3.))]),
                        Integer(4.into()),
                    ),
                ])
            ),
        );
    }
}