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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use crate::data::{EntityItem, ENTITIES};
use lazy_static::lazy_static;
#[cfg(target_arch = "wasm32")]
use num_derive::*;
#[cfg(target_arch = "wasm32")]
use num_traits::FromPrimitive;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;

type SortedEntity = Vec<EntityItem>;
type Positions = HashMap<u8, (usize, usize)>;

/// NOOP is the None value of Option<dyn Fn(char)->bool>  
pub const NOOP: Option<&dyn Fn(char) -> bool> = None::<&dyn Fn(char) -> bool>;

lazy_static! {
  static ref IS_SORTED: AtomicBool = AtomicBool::new(false);
  static ref DECODE_ENTITIES: Mutex<SortedEntity> = Mutex::new(vec![]);
  static ref FIRST_POSITION: Mutex<Positions> = Mutex::new(HashMap::new());
  // special chars
  static ref SPECIAL_CHARS: HashMap<char, &'static str> = {
    let mut map = HashMap::new();
    map.insert('>', "&gt;");
    map.insert('<', "&lt;");
    map.insert('"', "&quot;");
    map.insert('\'', "&apos;");
    map.insert('&', "&amp;");
    map
  };
}

/// Encode a character.
///
/// # Examples
///
/// ```
/// use htmlentity::entity::*;
///
/// let character = '<';
/// let char_encoded = encode_char(character, EncodeType::Named, NOOP);
/// assert_eq!(char_encoded, "&lt;");
///
/// let character = '<';
/// let char_encoded = encode_char(character, EncodeType::Decimal, NOOP);
/// assert_eq!(char_encoded, "&#60;");
///
/// let character = '<';
/// let char_encoded = encode_char(character, EncodeType::Hex, NOOP);
/// assert_eq!(char_encoded, "&#x3c;");
///
/// let character = '<';
/// let char_encoded = encode_char(character, EncodeType::Named, Some(|ch|ch == '<'));
/// assert_eq!(char_encoded, "<");
/// ```
pub fn encode_char<F>(ch: char, encode_type: EncodeType, exclude_fn: Option<F>) -> String
where
  F: Fn(char) -> bool,
{
  use EncodeType::*;
  let encode_type = encode_type as u8;
  let char_code = ch as u32;
  let mut result = String::with_capacity(5);
  if encode_type & (Named as u8) > 0 {
    let mut should_find_name = true;
    if let Some(exclude_fn) = exclude_fn {
      if exclude_fn(ch) {
        should_find_name = false;
      }
    }
    if should_find_name {
      let finded = (&ENTITIES[..]).binary_search_by_key(&char_code, |&(_, code)| code);
      if let Ok(index) = finded {
        let mut first_index = index;
        // find the first, short and lowercase
        loop {
          if first_index > 0 {
            let next_index = first_index - 1;
            let (_, cur_char_code) = ENTITIES[next_index];
            if cur_char_code != char_code {
              break;
            }
            first_index -= 1;
          } else {
            break;
          }
        }
        let (entity, _) = ENTITIES[first_index];
        result.push('&');
        result.push_str(entity);
        result.push(';');
        return result;
      }
    }
  }
  if encode_type & (Hex as u8) > 0 {
    let hex = format!("&#x{:x};", char_code);
    result.push_str(&hex);
    return result;
  }
  if encode_type & (Decimal as u8) > 0 {
    let dec = format!("&#{};", char_code);
    result.push_str(&dec);
    return result;
  }
  result.push(ch);
  result
}

#[cfg_attr(
  target_arch = "wasm32",
  wasm_bindgen,
  derive(Clone, Copy, FromPrimitive, PartialEq, PartialOrd)
)]
/// The type of characters you need encoded, default: `SpecialCharsAndNoASCII`
pub enum EntitySet {
  Empty = 0,
  All = 1,                    // encode all
  NoASCII = 2,                // encode character not ascii
  SpecialChars = 4,           // encode '<>&''
  SpecialCharsAndNoASCII = 6, // default
}

impl Default for EntitySet {
  fn default() -> Self {
    EntitySet::SpecialCharsAndNoASCII
  }
}

impl EntitySet {
  /// check if a character need encode by the encode type, and encode it if nessessary.
  pub fn filter(&self, ch: &char, encode_type: EncodeType) -> (bool, Option<String>) {
    use EntitySet::*;
    match self {
      SpecialChars => {
        let encode_type = encode_type as u8;
        if let Some(&v) = SPECIAL_CHARS.get(ch) {
          if (encode_type & EncodeType::Named as u8) > 0 {
            return (true, Some(v.into()));
          }
          return (true, None);
        }
        (false, None)
      }
      NoASCII => (*ch as u32 > 0x80, None),
      SpecialCharsAndNoASCII => {
        let (need_encode, result) = EntitySet::NoASCII.filter(ch, encode_type);
        if need_encode {
          return (need_encode, result);
        }
        EntitySet::SpecialChars.filter(ch, encode_type)
      }
      All => (true, None),
      Empty => (false, None),
    }
  }
  /// check if the set contains the character.
  pub fn contains(&self, ch: &char) -> bool {
    let (flag, _) = self.filter(ch, EncodeType::Decimal);
    flag
  }
}

#[cfg(target_arch = "wasm32")]
/// impl for number style enum
impl EntitySet {
  fn value(&self) -> u8 {
    *self as _
  }
}

#[cfg(target_arch = "wasm32")]
/// impl for number style enum, from u8
impl From<u8> for EntitySet {
  fn from(orig: u8) -> Self {
    Self::from_u8(orig).unwrap_or(EntitySet::Empty)
  }
}

/// Encode a html code's characters into entities.
///
/// # Examples
///
/// ```
/// use htmlentity::entity::*;
///
/// let html = "<div class='header'></div>";
/// let html_encoded = encode(html, EntitySet::SpecialChars, EncodeType::Named);
/// assert_eq!(html_encoded, "&lt;div class=&apos;header&apos;&gt;&lt;/div&gt;");
///
/// let html_decoded = decode(&html_encoded);
/// assert_eq!(html, html_decoded);
/// ```
pub fn encode(content: &str, entity_set: EntitySet, encode_type: EncodeType) -> String {
  let mut result = String::with_capacity(content.len() + 5);
  for ch in content.chars() {
    let (need_encode, encoded) = entity_set.filter(&ch, encode_type);
    if need_encode {
      if let Some(encoded) = encoded {
        result.push_str(&encoded);
      } else {
        let encoded = encode_char(ch, encode_type, NOOP);
        result.push_str(&encoded);
      }
    } else {
      result.push(ch);
    }
  }
  result
}

/// Short for `encode(content, EntitySet::default(), EncodeType::default())`
pub fn encode_default(content: &str) -> String {
  encode(content, Default::default(), Default::default())
}

/// Encode by filter functions.
/// Use the `filte_fn` to choose the character need to encode.
/// Use the `exclude_fn` to exclude characters you don't want to use named.
///
/// # Examples
///
/// ```
/// use htmlentity::entity::*;
///
/// let html = "<div class='header'></div>";
/// let html_encoded = encode_filter(html, |ch|{
///   // special characters but not '<'
///   ch != '<' && EntitySet::SpecialChars.contains(&ch)
/// }, EncodeType::Named, NOOP);
/// assert_eq!(html_encoded, "<div class=&apos;header&apos;&gt;</div&gt;");
///
/// // special characters, but exclude the single quote "'" use named.
/// let html = "<div class='header'></div>";
/// let html_encoded = encode_filter(html, |ch|{
///   EntitySet::SpecialChars.contains(&ch)
/// }, EncodeType::NamedOrDecimal, Some(|ch| ch == '\''));
/// assert_eq!(html_encoded, "&lt;div class=&#39;header&#39;&gt;&lt;/div&gt;");
/// ```
pub fn encode_filter<F: Fn(char) -> bool, C: Fn(char) -> bool>(
  content: &str,
  filter_fn: F,
  encode_type: EncodeType,
  exclude_fn: Option<C>,
) -> String {
  let mut result = String::with_capacity(content.len() + 5);
  for ch in content.chars() {
    if filter_fn(ch) {
      result.push_str(&encode_char(ch, encode_type, exclude_fn.as_ref()));
    } else {
      result.push(ch);
    }
  }
  result
}

/// encode with the Encoder function.
///
/// # Examples
/// ```
/// use htmlentity::entity::*;
///
/// let html = "<div class='header'></div>";
/// let html_encoded = encode_with(html, |ch:char|{
///   if(EntitySet::SpecialChars.contains(&ch)){
///     return Some(EncodeType::Named);
///   }
///   None
/// });
/// assert_eq!(html_encoded, "&lt;div class=&apos;header&apos;&gt;&lt;/div&gt;");
///
/// let html_decoded = decode(&html_encoded);
/// ```
pub fn encode_with<F>(content: &str, encoder: F) -> String
where
  F: Fn(char) -> Option<EncodeType>,
{
  let mut result = String::with_capacity(content.len() + 5);
  for ch in content.chars() {
    if let Some(encode_type) = encoder(ch) {
      result.push_str(&encode_char(ch, encode_type, NOOP));
    } else {
      result.push(ch);
    }
  }
  result
}
/**
 * Sort
 */
fn sort_entities() {
  let mut sorted: SortedEntity = Vec::with_capacity(ENTITIES.len());
  let mut counts: Positions = HashMap::new();
  let mut firsts: Vec<u8> = Vec::with_capacity(52);
  // binary search
  for pair in &ENTITIES[..] {
    let entity = *pair;
    let chars = entity.0.as_bytes();
    let first = chars[0];
    binary_insert(&mut sorted, entity);
    // save the first character index to HashMap
    match counts.get_mut(&first) {
      Some((v, _)) => {
        *v += 1;
      }
      None => {
        counts.insert(first, (1, 0));
      }
    }
    // insert
    if !firsts.contains(&first) {
      firsts.push(first);
    }
  }
  // sort
  firsts.sort_unstable();
  let mut cur_index: usize = 0;
  for char_code in firsts {
    let position = counts.get_mut(&char_code).unwrap();
    let next_index = cur_index + position.0;
    *position = (cur_index, next_index);
    cur_index = next_index;
  }
  // save index to positions
  let mut positions = FIRST_POSITION.lock().unwrap();
  *positions = counts;
  // save sorted entities
  let mut entities = DECODE_ENTITIES.lock().unwrap();
  *entities = sorted;
}
/**
 * binary insert
 */
fn binary_insert(sorted: &mut SortedEntity, cur: EntityItem) {
  let mut prev_index = 0;
  let len = sorted.len();
  if len > 0 {
    let search = cur.0;
    prev_index = match sorted[..].binary_search_by(|&(name, _)| name.cmp(search)) {
      Ok(index) => index,
      Err(index) => index,
    };
  }
  (*sorted).insert(prev_index, cur);
}

#[derive(PartialEq, Eq)]
pub enum EntityIn {
  Unkown,
  Named,
  Hex,
  Decimal,
  HexOrDecimal,
}
/// EncodeType: the output format type, default: `NamedOrDecimal`
#[cfg_attr(
  target_arch = "wasm32",
  wasm_bindgen,
  derive(FromPrimitive, PartialEq, PartialOrd)
)]
#[derive(Copy, Clone)]
pub enum EncodeType {
  Ignore = 0,
  Named = 0b00001,
  Hex = 0b00010,
  Decimal = 0b00100,
  NamedOrHex = 0b00011,
  NamedOrDecimal = 0b00101,
}

impl Default for EncodeType {
  fn default() -> Self {
    EncodeType::NamedOrDecimal
  }
}

#[cfg(target_arch = "wasm32")]
/// impl for number style enum
impl EncodeType {
  fn value(&self) -> u8 {
    *self as _
  }
}

#[cfg(target_arch = "wasm32")]
/// impl for number style enum, from u8
impl From<u8> for EncodeType {
  fn from(orig: u8) -> Self {
    Self::from_u8(orig).unwrap_or(EncodeType::Ignore)
  }
}

/// Decode character list, replace the entity characters into a unicode character.
///
/// # Examples
///
/// ```
/// use htmlentity::entity::*;
///
/// let char_list = vec!['<'];
/// assert_eq!(decode_chars("&lt;".chars().collect::<Vec<char>>()), char_list);
/// assert_eq!(decode_chars("&#60;".chars().collect::<Vec<char>>()), char_list);
/// assert_eq!(decode_chars("&#x3c;".chars().collect::<Vec<char>>()), char_list);
/// ```
pub fn decode_chars(chars: Vec<char>) -> Vec<char> {
  let mut result: Vec<char> = Vec::with_capacity(chars.len());
  let mut entity: Entity = Entity::new();
  let mut is_in_entity: bool = false;
  for ch in chars {
    if !is_in_entity {
      if entity.add(ch) {
        is_in_entity = true;
      } else {
        result.push(ch);
      }
    } else {
      let is_wrong_entity = !entity.add(ch);
      if is_wrong_entity || entity.is_end {
        result.extend(entity.get_chars());
        if is_wrong_entity {
          result.push(ch);
        }
        is_in_entity = false;
        entity = Entity::new();
      }
    }
  }
  // still in entity at the end
  if is_in_entity {
    result.extend(entity.get_chars());
  }
  result
}

/// Decode a html code's entities into unicode characters, include the `Decimal` `Hex` `Named`.
///
/// # Examples
///
/// ```
/// use htmlentity::entity::*;
///
/// let content = "<";
/// assert_eq!(decode("&lt;"), content);
/// assert_eq!(decode("&#60;"), content);
/// assert_eq!(decode("&#x3c;"), content);
/// ```
pub fn decode(content: &str) -> String {
  let chars: Vec<char> = content.chars().collect();
  decode_chars(chars).into_iter().collect::<String>()
}
/// Entity struct
#[derive(Default)]
pub struct Entity {
  pub entity_in: Option<EntityIn>,
  pub characters: Vec<char>,
  pub is_end: bool,
}

impl Entity {
  /// Return an Entity struct, same as Entity::default()
  pub fn new() -> Self {
    Entity::default()
  }
  /// `add(ch: char)`: check if the character is an allowed character
  pub fn add(&mut self, ch: char) -> bool {
    if self.is_end {
      return false;
    }
    use EntityIn::*;
    if let Some(entity_in) = &self.entity_in {
      let mut is_in_entity = true;
      if ch == ';' {
        self.is_end = true;
        return true;
      } else {
        match entity_in {
          Named => {
            if !ch.is_ascii_alphabetic() {
              is_in_entity = false;
            }
          }
          Hex | Decimal => match ch {
            '0'..='9' => {}
            'a'..='f' | 'A'..='F' if entity_in == &Hex => {}
            _ => {
              is_in_entity = false;
            }
          },
          Unkown => {
            if ch.is_ascii_alphabetic() {
              self.entity_in = Some(Named);
            } else if ch == '#' {
              self.entity_in = Some(HexOrDecimal);
            } else {
              is_in_entity = false;
            }
          }
          HexOrDecimal => match ch {
            '0'..='9' => {
              self.entity_in = Some(Decimal);
            }
            'x' | 'X' => {
              self.entity_in = Some(Hex);
            }
            _ => {
              is_in_entity = false;
            }
          },
        };
        if is_in_entity {
          self.characters.push(ch);
        }
        return is_in_entity;
      }
    } else if ch == '&' {
      self.entity_in = Some(Unkown);
      return true;
    }
    false
  }
  /// `decode()`: decode the entity, if ok, return the unicode character.
  pub fn decode(&self) -> Option<char> {
    if !self.is_end {
      return None;
    }
    use EntityIn::*;
    let entity = &self.characters;
    let entity_in = self.entity_in.as_ref().unwrap();
    match entity_in {
      Named => {
        // try to find the entity
        let first = entity[0] as u32 as u8;
        // sort the named characters
        let is_sorted = IS_SORTED.load(Ordering::SeqCst);
        if !is_sorted {
          sort_entities();
          IS_SORTED.store(true, Ordering::SeqCst);
        }
        let sorted = DECODE_ENTITIES.lock().unwrap();
        let firsts = FIRST_POSITION.lock().unwrap();
        if let Some(&(start_index, end_index)) = firsts.get(&first) {
          let searched = entity.iter().collect::<String>();
          if let Ok(find_index) = sorted[start_index..end_index]
            .binary_search_by(|&(name, _)| name.cmp(searched.as_str()))
          {
            let last_index = start_index + find_index;
            let (_, code) = sorted[last_index];
            return Some(std::char::from_u32(code).unwrap());
          }
        }
      }
      Hex | Decimal => {
        let base_type: u32;
        let numbers: &[char];
        if entity_in == &Hex {
          base_type = 16;
          // remove the prefix '#x'
          numbers = &entity[2..];
        } else {
          base_type = 10;
          // remove the prefix '#'
          numbers = &entity[1..];
        }
        if numbers.is_empty() {
          // '&#;' '&#x;'
          return None;
        }
        let numbers = numbers.iter().collect::<String>();
        if let Ok(char_code) = i64::from_str_radix(&numbers, base_type) {
          if (0..=0x10ffff).contains(&char_code) {
            if let Some(last_ch) = std::char::from_u32(char_code as u32) {
              return Some(last_ch);
            }
          }
        }
      }
      _ => {
        // entity '&;' '&#'
      }
    }
    None
  }
  /// `get_chars()` return the characters of the entity,if it's a correct entity, it will return the Vec with the decoded unicode character, otherwise return all the characters.
  pub fn get_chars(&self) -> Vec<char> {
    if let Some(ch) = self.decode() {
      return vec![ch];
    }
    let is_end = self.is_end;
    let mut result = Vec::with_capacity(self.characters.len() + 1 + is_end as usize);
    result.push('&');
    result.extend(&self.characters);
    if is_end {
      result.push(';');
    }
    result
  }
}