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
321
322
323
324
325
326
327
328
// Copyright 2016  Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

//! Handles ASCII characters.

pub mod table;

use std::error;
use std::error::Error;
use std::fmt;

/// Defines the methods for ASCII operations on characters.
pub trait Check {
    /// `is_letter` checks whether it is an ASCII letter (a-z / A-Z).
    fn is_letter(self) -> bool;
    /// `is_lower` checks whether it is an ASCII lower case letter (a-z).
    fn is_lower(self) -> bool;
    /// `is_upper` checks whether it is an ASCII upper case letter (A-Z).
    fn is_upper(self) -> bool;
    /// `is_digit` checks whether it is an ASCII digit (0-9).
    fn is_digit(self) -> bool;
    /// `is_space` checks whether it is an ASCII space character
    /// (Space, Horizontal Tab, Line Feed, Vertical Tab, Form Feed, Carriage Return).
    fn is_space(self) -> bool;

    /// `is_control` checks whether it is an ASCII control character.
    /// The control characters are unprintable control codes and are used
    /// to control peripherals such as printers.
    fn is_control(self) -> bool;

    /// `is_printable` checks whether it is an ASCII printable character.
    /// The printable characters are common for all the different variations
    /// of the ASCII table; represent letters, digits, punctuation marks,
    /// and a few miscellaneous symbols.
    fn is_printable(self) -> bool;

    /// `is_us_ascii` checks whether it is an US-ASCII character.
    fn is_us_ascii(self) -> bool;

    /// `is_extended` checks whether it is an extended ASCII character.
    fn is_extended(self) -> bool;
}

impl Check for u8 {
    fn is_letter(self) -> bool {
        match self {
            b'a'...b'z' | b'A'...b'Z' => true,
            _ => false,
        }
    }

    fn is_lower(self) -> bool {
        match self {
            b'a'...b'z' => true,
            _ => false,
        }
    }

    fn is_upper(self) -> bool {
        match self {
            b'A'...b'Z' => true,
            _ => false,
        }
    }

    fn is_digit(self) -> bool {
        match self {
            b'0'...b'9' => true,
            _ => false,
        }
    }

    fn is_space(self) -> bool {
        match self {
            table::SPACE | 0x09...0x0D => true,
            _ => false,
        }
    }

    fn is_control(self) -> bool {
        match self {
            0x00...0x1F | 0x7F => true,
            _ => false,
        }
    }

    fn is_printable(self) -> bool {
        match self {
            0x20...0x7E => true,
            _ => false,
        }
    }

    fn is_us_ascii(self) -> bool {
        match self {
            0x00...0x7F => true,
            _ => false,
        }
    }

    fn is_extended(self) -> bool {
        match self {
            0x80...0xFF => true,
            _ => false,
        }
    }
}

impl Check for char {
    fn is_letter(self) -> bool {
        match self {
            'a'...'z' | 'A'...'Z' => true,
            _ => false,
        }
    }

    fn is_lower(self) -> bool {
        match self {
            'a'...'z' => true,
            _ => false,
        }
    }

    fn is_upper(self) -> bool {
        match self {
            'A'...'Z' => true,
            _ => false,
        }
    }

    fn is_digit(self) -> bool {
        match self {
            '0'...'9' => true,
            _ => false,
        }
    }

    fn is_space(self) -> bool {
        match self {
            table::SPACE_CHAR |
            '\u{9}'...'\u{D}' => true,
            _ => false,
        }
    }

    fn is_control(self) -> bool {
        match self as u8 {
            0x00...0x1F | 0x7F => true,
            _ => false,
        }
    }

    fn is_printable(self) -> bool {
        match self as u8 {
            0x20...0x7E => true,
            _ => false,
        }
    }

    fn is_us_ascii(self) -> bool {
        match self as u8 {
            0x00...0x7F => true,
            _ => false,
        }
    }

    fn is_extended(self) -> bool {
        match self as u8 {
            0x80...0xFF => true,
            _ => false,
        }
    }
}

/// Reports an error wheter the string has a non-ASCII character or any ASCII
/// control character.
pub fn check_ascii_printable(name: &str) -> Result<(), AsciiError> {
    let mut i: usize = 0;

    for byte in name.bytes() {
        match byte {
            0x20...0x7E => (),
            0x00...0x1F | 0x7F => return Err(AsciiError::ControlChar(i + 1)),
            _ => {
                match name[i..].chars().next() {
                    Some(v) => return Err(AsciiError::NonAscii(v)),
                    None => unreachable!(),
                }
            }
        }
        i = i + 1;
    }

    Ok(())
}

// == Errors
//

#[derive(Debug, PartialEq, Eq)]
pub enum AsciiError {
    NonAscii(char),
    ControlChar(usize),
}

impl error::Error for AsciiError {
    fn description(&self) -> &str {
        match *self {
            AsciiError::NonAscii(_) => "contain non US-ASCII character",
            AsciiError::ControlChar(_) => "contain ASCII control character",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        None
    }
}

impl fmt::Display for AsciiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch),
            AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos),
        }
    }
}

// == Tests
//

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

    #[test]
    fn test_letter() {
        assert!(Check::is_letter(b'a'));
        assert!(Check::is_letter('j'));
        assert!(Check::is_letter('Z'));

        assert_eq!('0'.is_letter(), false);
    }

    #[test]
    fn test_lower() {
        assert!(Check::is_lower(b'a'));
        assert!(Check::is_lower('z'));

        assert_eq!(Check::is_lower('J'), false);
    }

    #[test]
    fn test_upper() {
        assert!(Check::is_upper(b'A'));
        assert!(Check::is_upper('Z'));

        assert_eq!(Check::is_upper('j'), false);
    }

    #[test]
    fn test_digit() {
        assert!(Check::is_digit(b'0'));
        assert!(Check::is_digit('5'));
        assert!(Check::is_digit('9'));

        assert_eq!(Check::is_digit('a'), false)
    }

    #[test]
    fn test_space() {
        assert!(Check::is_space(table::HT));
        assert!(Check::is_space(table::SPACE));

        assert_eq!(Check::is_space(b'a'), false);
        assert_eq!(Check::is_space('-'), false);
    }

    #[test]
    fn test_control() {
        assert_eq!(Check::is_control('a'), false);
    }

    #[test]
    fn test_printable() {
        assert!(Check::is_printable(b'J'));
        assert!(Check::is_printable('0'));
        assert!(Check::is_printable('-'));

        assert_eq!(Check::is_printable(table::DELETE), false);
    }

    #[test]
    fn test_us_ascii() {
        assert!(Check::is_us_ascii('a'));

        assert_eq!(Check::is_us_ascii('€'), false);
    }

    #[test]
    fn test_extended() {
        assert!(Check::is_extended('€'));

        assert_eq!(Check::is_extended('a'), false);
    }

    #[test]
    fn test_check_ascii_printable() {
        check_ascii_printable("aeiou").unwrap();

        assert_eq!(check_ascii_printable("äeiou"),
                   Err(AsciiError::NonAscii('ä')));
        assert_eq!(check_ascii_printable("aeïou"),
                   Err(AsciiError::NonAscii('ï')));
        assert_eq!(check_ascii_printable("aeioü"),
                   Err(AsciiError::NonAscii('ü')));
        assert_eq!(check_ascii_printable("foo€bar"),
                   Err(AsciiError::NonAscii('€')));
        assert_eq!(check_ascii_printable("foo♦bar"),
                   Err(AsciiError::NonAscii('♦')));

        assert_eq!(check_ascii_printable("foo\tbar"),
                   Err(AsciiError::ControlChar(4)));
    }
}