use std::num::ParseIntError;
#[derive(Debug, PartialEq)]
enum Error {
Int(ParseIntError),
Unicode(u32),
}
fn parse_unicode(input: &str) -> Result<char, Error> {
let unicode = u32::from_str_radix(input, 10).map_err(Error::Int)?;
char::from_u32(unicode).ok_or_else(|| Error::Unicode(unicode))
}
pub fn decode(u: &str) -> String {
u.split(';')
.map(|item| {
let u = item.replace("&#", "");
match parse_unicode(&u) {
Ok(x) => x.to_string(),
Err(_) => "".to_string(),
}
})
.collect::<Vec<String>>()
.join("")
}
pub fn encode(s: &str) -> String {
s.chars()
.map(|c| format!("&#{};", c as u32))
.collect::<Vec<String>>()
.join("")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_decode() {
let a = "测试".to_string();
let b = "测试";
let c = decode(b);
assert_eq!(a, c)
}
#[test]
fn test_encode() {
let a = "测试";
let b = "测试".to_string();
let c = encode(a);
assert_eq!(b, c)
}
#[test]
fn test_parse_unicode() {
assert_eq!(parse_unicode("128077"), Ok('👍'));
}
}