Crates.io | htmlentity |
lib.rs | htmlentity |
version | 1.3.2 |
source | src |
created_at | 2020-11-22 15:33:06.357134 |
updated_at | 2024-06-07 07:19:50.45447 |
description | A library for encoding and decoding HTML entities. |
homepage | https://github.com/fefit/htmlentity |
repository | https://github.com/fefit/htmlentity |
max_upload_size | |
id | 315032 |
size | 168,394 |
A library for encoding and decoding HTML entities.
use htmlentity::entity::{ encode, decode, EncodeType, CharacterSet, ICodedDataTrait };
use htmlentity::types::{ AnyhowResult, Byte };
fn main() -> AnyhowResult<()> {
let html = "<div name='htmlentity'>Hello!世界!</div>";
let html_after_encoded = "<div name='htmlentity'>Hello!世界!</div>";
// encode
let encoded_data = encode(
html.as_bytes(),
// encode format
&EncodeType::NamedOrHex,
// charcters need to be encoded
&CharacterSet::HtmlAndNonASCII
);
assert_eq!(encoded_data.to_bytes(), html_after_encoded.as_bytes());
assert_eq!(encoded_data.to_string()?, String::from(html_after_encoded));
let char_list = String::from(html_after_encoded).chars().collect::<Vec<char>>();
assert_eq!(encoded_data.to_chars()?, char_list);
// decode
let bytes = encoded_data.into_iter().map(|(byte, _)| *byte).collect::<Vec<Byte>>();
let decoded_data = decode(&bytes);
assert_eq!(decoded_data.to_bytes(), html.as_bytes());
assert_eq!(decoded_data.to_string()?, String::from(html));
let char_list = String::from(html).chars().collect::<Vec<char>>();
assert_eq!(decoded_data.to_chars()?, char_list);
// shortcut usage
assert_eq!(
encode(
html.as_bytes(),
&EncodeType::NamedOrHex,
&CharacterSet::HtmlAndNonASCII,
).to_string()?,
String::from(html)
);
Ok(())
}
For more details, please see the document in Docs.rs