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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use std::io::{self, Write, BufRead, Cursor};
use std::char;
use self::DecodeState::*;
use self::DecodeErrKind::*;
use io_support::{self, write_char, CharsError};
use entities::*;

#[derive(Debug)]
pub enum DecodeErrKind {
    /// A non-existent named entity was referenced.
    /// Example: &thisentitydoesnotexist
    UnknownEntity,

    /// A numerical escape sequence (&# or &#x) containing an invalid character.
    /// Examples: `&#32a`, `&#xfoo`
    MalformedNumEscape,

    /// A numerical escape sequence (&# or &#x) resolved to an invalid unicode code point.
    /// Example: `&#xffffff`
    InvalidCharacter,

    /// The input ended prematurely (ie. inside an unterminated named entity sequence).
    PrematureEnd,

    /// An IO error occured.
    IoError(io::Error),

    /// The supplied Reader produces invalid UTF-8.
    EncodingError,
}

impl PartialEq for DecodeErrKind {
    fn eq(&self, other: &DecodeErrKind) -> bool {
        match (self, other) {
            (&UnknownEntity, &UnknownEntity) => true,
            (&MalformedNumEscape, &MalformedNumEscape) => true,
            (&InvalidCharacter, &InvalidCharacter) => true,
            (&PrematureEnd, &PrematureEnd) => true,
            (&IoError(_), &IoError(_)) => true,
            (&EncodingError, &EncodingError) => true,
            _ => false
        }
    }
}

impl Eq for DecodeErrKind {}

/// Error from decoding a entity-encoded string.
#[derive(Debug, Eq, PartialEq)]
pub struct DecodeErr {
    /// Number of characters read from the input before encountering an error
    pub position: usize,
    /// Type of error
    pub kind: DecodeErrKind
}

#[derive(PartialEq, Eq)]
enum DecodeState {
    Normal,
    Entity,
    Named,
    Numeric,
    Hex,
    Dec
}

macro_rules! try_parse(
    ($parse:expr, $pos:expr) => (
        match $parse {
            Err(reason) => return Err(DecodeErr{ position: $pos, kind: reason}),
            Ok(res) => res
        }
    ););

macro_rules! try_dec_io(
    ($io:expr, $pos:expr) => (
        match $io {
            Err(e) => return Err(DecodeErr{ position: $pos, kind: IoError(e)}),
            Ok(res) => res
        }
    ););

/// Decodes an entity-encoded string from a reader to a writer.
///
/// Similar to `decode_html`, except reading from a reader rather than a string, and
/// writing to a writer rather than returning a `String`.
///
/// # Arguments
/// - `reader` - UTF-8 encoded data is read from here.
/// - `writer` - UTF8- decoded data is written to here.
///
/// # Errors
/// Errors can be caused by IO errors, `reader` producing invalid UTF-8, or by syntax errors.
pub fn decode_html_rw<R: BufRead, W: Write>(reader: R, writer: &mut W) -> Result<(), DecodeErr> {
    let mut state: DecodeState = Normal;
    let mut pos = 0;
    let mut good_pos = 0;
    let mut buf = String::with_capacity(8);
    for c in io_support::chars(reader) {
        let c = match c {
            Err(e) => {
                let kind = match e {
                    CharsError::NotUtf8   => EncodingError,
                    CharsError::Other(io) => IoError(io)
                };
                return Err(DecodeErr{ position: pos, kind: kind });
            }
            Ok(c) => c
        };
        match state {
            Normal if c == '&' => state = Entity,
            Normal => try_dec_io!(write_char(writer, c), good_pos),
            Entity if c == '#' => state = Numeric,
            Entity if c == ';' => return Err(DecodeErr{ position: good_pos, kind: UnknownEntity }),
            Entity => {
                state = Named;
                buf.push(c);
            }
            Named if c == ';' => {
                state = Normal;
                let ch = try_parse!(decode_named_entity(&buf), good_pos);
                try_dec_io!(write_char(writer, ch), good_pos);
                buf.clear();
            }
            Named => buf.push(c),
            Numeric if is_digit(c) => {
                state = Dec;
                buf.push(c);
            }
            Numeric if c == 'x' => state = Hex,
            Dec if c == ';' => {
                state = Normal;
                let ch = try_parse!(decode_numeric(&buf, 10), good_pos);
                try_dec_io!(write_char(writer, ch), good_pos);
                buf.clear();
            }
            Hex if c == ';' => {
                state = Normal;
                let ch = try_parse!(decode_numeric(&buf, 16), good_pos);
                try_dec_io!(write_char(writer, ch), good_pos);
                buf.clear();
            }
            Hex if is_hex_digit(c) => buf.push(c),
            Dec if is_digit(c) => buf.push(c),
            Numeric | Hex | Dec => return Err(DecodeErr{ position: good_pos, kind: MalformedNumEscape}),
        }
        pos += 1;
        if state == Normal {
            good_pos = pos;
        }
    }
    if state != Normal {
        Err(DecodeErr{ position: good_pos, kind: PrematureEnd})
    } else {
        Ok(())
    }
}


/// Decodes an entity-encoded string from a reader to a writer ignoring errors.
/// Properly written and recognised entities will be decoded,
/// any partial or unknown ones will be left intact.
///
/// Similar to `decode_html`, except reading from a reader rather than a string, and
/// writing to a writer rather than returning a `String`.
///
/// # Arguments
/// - `reader` - UTF-8 encoded data is read from here.
/// - `writer` - UTF8- decoded data is written to here.
///
/// # Errors
/// Errors can be caused by IO errors, `reader` producing invalid UTF-8.
pub fn decode_html_rw_ignoring_errors<R: BufRead, W: Write>(reader: R, writer: &mut W) -> Result<(), DecodeErr> {
    let mut state: DecodeState = Normal;
    let mut pos = 0;
    let mut good_pos = 0;
    let mut buf = String::with_capacity(8);
    let mut buf_since_good_pos = String::with_capacity(20);
    for c in io_support::chars(reader) {
        let c = match c {
            Err(e) => {
                let kind = match e {
                    CharsError::NotUtf8   => EncodingError,
                    CharsError::Other(io) => IoError(io)
                };
                return Err(DecodeErr{ position: pos, kind: kind });
            }
            Ok(c) => c
        };
        match state {
            Normal if c == '&' => { buf_since_good_pos.push(c); state = Entity},
            Normal => try_dec_io!(write_char(writer, c), good_pos),
            Entity if c == '#' => { buf_since_good_pos.push(c); state = Numeric},
            Entity if c == ';' => {
                buf_since_good_pos.push(c);
                try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos);
                buf_since_good_pos.clear();
                state = Normal
            }
            Entity => {
                state = Named;
                buf.push(c);
                buf_since_good_pos.push(c);
            }
            Named if c == ';' => {
                state = Normal;
                match  decode_named_entity(&buf) {
                    Ok(ch) => {
                        try_dec_io!(write_char(writer, ch), good_pos);
                        buf.clear();
                        buf_since_good_pos.clear();
                    },
                    Err(_) => {
                        buf_since_good_pos.push(c);
                        try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos);
                        buf_since_good_pos.clear();
                        buf.clear();
                    }
                }
            }
            Named => {
                buf.push(c);
                buf_since_good_pos.push(c);
            },
            Numeric if is_digit(c) => {
                state = Dec;
                buf.push(c);
                buf_since_good_pos.push(c);
            }
            Numeric if c == 'x' => {
                buf_since_good_pos.push(c);
                state = Hex
            },
            Dec if c == ';' => {
                state = Normal;
                match  decode_numeric(&buf, 10) {
                    Ok(ch) => {
                        try_dec_io!(write_char(writer, ch), good_pos);
                        buf.clear();
                        buf_since_good_pos.clear();
                    },
                    Err(_) => {
                        buf_since_good_pos.push(c);
                        try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos);
                        buf_since_good_pos.clear();
                        buf.clear();
                    }
                }
            }
            Hex if c == ';' => {
                state = Normal;
                match  decode_numeric(&buf, 16) {
                    Ok(ch) => {
                        try_dec_io!(write_char(writer, ch), good_pos);
                        buf.clear();
                        buf_since_good_pos.clear();
                    },
                    Err(_) => {
                        buf_since_good_pos.push(c);
                        try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos);
                        buf_since_good_pos.clear();
                        buf.clear();
                    }
                }
            }
            Hex if is_hex_digit(c) => { buf.push(c); buf_since_good_pos.push(c) },
            Dec if is_digit(c) => { buf.push(c); buf_since_good_pos.push(c) },
            Numeric | Hex | Dec => {
                buf_since_good_pos.push(c);
                try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos);
                buf_since_good_pos.clear();
                buf.clear();
                state = Normal
            }
        }
        pos += 1;
        if state == Normal {
            good_pos = pos;
        }
    }

    if state != Normal {
        //let slice = reader;
        try_dec_io!(writer.write(buf_since_good_pos.as_bytes()), good_pos); 
    }
    
    Ok(())
}


/// Decodes an entity-encoded string.
///
/// Decodes an entity encoded string, replacing HTML entities (`&amp;`, `&#20;` ...) with the
/// the corresponding character. Case matters for named entities, ie. `&Amp;` is invalid.
/// Case does not matter for hex entities, so `&#x2E;` and `&#x2e;` are treated the same.
///
/// # Arguments
/// - `s` - Entity-encoded string to decode.
///
/// # Failure
/// The function will fail if input string contains invalid named entities (eg. `&nosuchentity;`),
/// invalid hex entities (eg. `&#xRT;`), invalid decimal entities (eg. `&#-1;), unclosed entities
/// (`s == "&amp hej och hå"`) or otherwise malformed entities.
///
/// This function will never return errors with `kind` set to `IoError` or `EncodingError`.
pub fn decode_html(s: &str) -> Result<String, DecodeErr> {
    let mut writer = Vec::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut reader = Cursor::new(bytes);
    let res = decode_html_rw(&mut reader, &mut writer);
    match res {
        Ok(_) => Ok(String::from_utf8(writer).unwrap()),
        Err(err) => Err(err)
    }
}

/// Decodes an entity-encoded string.
///
/// Decodes an entity encoded string, replacing HTML entities (`&amp;`, `&#20;` ...) with the
/// the corresponding character. Case matters for named entities, ie. `&Amp;` is invalid.
/// Case does not matter for hex entities, so `&#x2E;` and `&#x2e;` are treated the same.
///
/// # Arguments
/// - `s` - Entity-encoded string to decode.
///
/// # Failure
/// Any invalid, unrecognised or malformed entities will be ignored and left intact.
///
/// This function will never return errors with `kind` set to `IoError` or `EncodingError`.
pub fn decode_html_ignoring_errors(s: &str) -> Result<String, DecodeErr> {
    let mut writer = Vec::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut reader = Cursor::new(bytes);
    let res = decode_html_rw_ignoring_errors(&mut reader, &mut writer);
    match res {
        Ok(_) => Ok(String::from_utf8(writer).unwrap()),
        Err(err) => Err(err)
    }
}

fn is_digit(c: char) -> bool { c >= '0' && c <= '9' }

fn is_hex_digit(c: char) -> bool {
    is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}

fn decode_named_entity(entity: &str) -> Result<char, DecodeErrKind> {
    match NAMED_ENTITIES.binary_search_by(|&(ent, _)| ent.cmp(entity)) {
        Err(..) => Err(UnknownEntity),
        Ok(idx) => {
            let (_, c) = NAMED_ENTITIES[idx];
            Ok(c)
        }
    }
}

fn decode_numeric(esc: &str, radix: u32) -> Result<char, DecodeErrKind> {
    match u32::from_str_radix(esc, radix) {
        Ok(n) => match char::from_u32(n) {
            Some(c) => Ok(c),
            None => Err(InvalidCharacter)
        },
        Err(..) => Err(MalformedNumEscape)
    }
}