aboutsummaryrefslogtreecommitdiffstats
path: root/src/util/encode.rs
diff options
context:
space:
mode:
authorLibravatar Titus Wormer <tituswormer@gmail.com>2022-07-05 13:03:09 +0200
committerLibravatar Titus Wormer <tituswormer@gmail.com>2022-07-05 13:03:09 +0200
commitfd860a975b84da9a79abfa247787e6adbd5ea34c (patch)
treebd9db168c57478f4f37c234eac4087c2d69a6445 /src/util/encode.rs
parent0bc099f8f8b6541a962e604b7ac25445a2a9252a (diff)
downloadmarkdown-rs-fd860a975b84da9a79abfa247787e6adbd5ea34c.tar.gz
markdown-rs-fd860a975b84da9a79abfa247787e6adbd5ea34c.tar.bz2
markdown-rs-fd860a975b84da9a79abfa247787e6adbd5ea34c.zip
Refactor code style
Diffstat (limited to '')
-rw-r--r--src/util/encode.rs39
1 files changed, 32 insertions, 7 deletions
diff --git a/src/util/encode.rs b/src/util/encode.rs
index 5762c22..a3bd589 100644
--- a/src/util/encode.rs
+++ b/src/util/encode.rs
@@ -21,11 +21,36 @@
///
/// * [`micromark-util-encode` in `micromark`](https://github.com/micromark/micromark/tree/main/packages/micromark-util-encode)
pub fn encode(value: &str) -> String {
- // To do: replacing 4 times might just be slow.
- // Perhaps we can walk the chars.
- value
- .replace('&', "&amp;")
- .replace('"', "&quot;")
- .replace('<', "&lt;")
- .replace('>', "&gt;")
+ let mut result: Vec<&str> = vec![];
+ let mut start = 0;
+ let mut index = 0;
+
+ for byte in value.bytes() {
+ if let Some(replacement) = match byte {
+ b'&' => Some("&amp;"),
+ b'"' => Some("&quot;"),
+ b'<' => Some("&lt;"),
+ b'>' => Some("&gt;"),
+ _ => None,
+ } {
+ if start != index {
+ result.push(&value[start..index]);
+ }
+
+ result.push(replacement);
+ start = index + 1;
+ }
+
+ index += 1;
+ }
+
+ if start == 0 {
+ value.to_string()
+ } else {
+ if start < index {
+ result.push(&value[start..index]);
+ }
+
+ result.join("")
+ }
}