/rust/registry/src/index.crates.io-6f17d22bba15001f/urlencoding-2.1.3/src/enc.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use std::borrow::Cow; |
2 | | use std::fmt; |
3 | | use std::io; |
4 | | use std::str; |
5 | | |
6 | | /// Wrapper type that implements `Display`. Encodes on the fly, without allocating. |
7 | | /// Percent-encodes every byte except alphanumerics and `-`, `_`, `.`, `~`. Assumes UTF-8 encoding. |
8 | | /// |
9 | | /// ```rust |
10 | | /// use urlencoding::Encoded; |
11 | | /// format!("{}", Encoded("hello!")); |
12 | | /// ``` |
13 | | #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)] |
14 | | #[repr(transparent)] |
15 | | pub struct Encoded<Str>(pub Str); |
16 | | |
17 | | impl<Str: AsRef<[u8]>> Encoded<Str> { |
18 | | /// Long way of writing `Encoded(data)` |
19 | | /// |
20 | | /// Takes any string-like type or a slice of bytes, either owned or borrowed. |
21 | | #[inline(always)] |
22 | 0 | pub fn new(string: Str) -> Self { |
23 | 0 | Self(string) |
24 | 0 | } |
25 | | |
26 | | #[inline(always)] |
27 | 0 | pub fn to_str(&self) -> Cow<str> { |
28 | 0 | encode_binary(self.0.as_ref()) |
29 | 0 | } |
30 | | |
31 | | /// Perform urlencoding to a string |
32 | | #[inline] |
33 | | #[allow(clippy::inherent_to_string_shadow_display)] |
34 | 0 | pub fn to_string(&self) -> String { |
35 | 0 | self.to_str().into_owned() |
36 | 0 | } |
37 | | |
38 | | /// Perform urlencoding into a writer |
39 | | #[inline] |
40 | 0 | pub fn write<W: io::Write>(&self, writer: &mut W) -> io::Result<()> { |
41 | 0 | encode_into(self.0.as_ref(), false, |s| writer.write_all(s.as_bytes()))?; |
42 | 0 | Ok(()) |
43 | 0 | } |
44 | | |
45 | | /// Perform urlencoding into a string |
46 | | #[inline] |
47 | 0 | pub fn append_to(&self, string: &mut String) { |
48 | 0 | append_string(self.0.as_ref(), string, false); |
49 | 0 | } |
50 | | } |
51 | | |
52 | | impl<'a> Encoded<&'a str> { |
53 | | /// Same as new, but hints a more specific type, so you can avoid errors about `AsRef<[u8]>` not implemented |
54 | | /// on references-to-references. |
55 | | #[inline(always)] |
56 | 0 | pub fn str(string: &'a str) -> Self { |
57 | 0 | Self(string) |
58 | 0 | } |
59 | | } |
60 | | |
61 | | impl<String: AsRef<[u8]>> fmt::Display for Encoded<String> { |
62 | 0 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
63 | 0 | encode_into(self.0.as_ref(), false, |s| f.write_str(s))?; |
64 | 0 | Ok(()) |
65 | 0 | } |
66 | | } |
67 | | |
68 | | /// Percent-encodes every byte except alphanumerics and `-`, `_`, `.`, `~`. Assumes UTF-8 encoding. |
69 | | /// |
70 | | /// Call `.into_owned()` if you need a `String` |
71 | | #[inline(always)] |
72 | 0 | pub fn encode(data: &str) -> Cow<str> { |
73 | 0 | encode_binary(data.as_bytes()) |
74 | 0 | } |
75 | | |
76 | | /// Percent-encodes every byte except alphanumerics and `-`, `_`, `.`, `~`. |
77 | | #[inline] |
78 | 674k | pub fn encode_binary(data: &[u8]) -> Cow<str> { |
79 | 674k | // add maybe extra capacity, but try not to exceed allocator's bucket size |
80 | 674k | let mut escaped = String::with_capacity(data.len() | 15); |
81 | 674k | let unmodified = append_string(data, &mut escaped, true); |
82 | 674k | if unmodified { |
83 | 6.04k | return Cow::Borrowed(unsafe { |
84 | 6.04k | // encode_into has checked it's ASCII |
85 | 6.04k | str::from_utf8_unchecked(data) |
86 | 6.04k | }); |
87 | 668k | } |
88 | 668k | Cow::Owned(escaped) |
89 | 674k | } Unexecuted instantiation: urlencoding::enc::encode_binary urlencoding::enc::encode_binary Line | Count | Source | 78 | 674k | pub fn encode_binary(data: &[u8]) -> Cow<str> { | 79 | 674k | // add maybe extra capacity, but try not to exceed allocator's bucket size | 80 | 674k | let mut escaped = String::with_capacity(data.len() | 15); | 81 | 674k | let unmodified = append_string(data, &mut escaped, true); | 82 | 674k | if unmodified { | 83 | 6.04k | return Cow::Borrowed(unsafe { | 84 | 6.04k | // encode_into has checked it's ASCII | 85 | 6.04k | str::from_utf8_unchecked(data) | 86 | 6.04k | }); | 87 | 668k | } | 88 | 668k | Cow::Owned(escaped) | 89 | 674k | } |
Unexecuted instantiation: urlencoding::enc::encode_binary |
90 | | |
91 | 674k | fn append_string(data: &[u8], escaped: &mut String, may_skip: bool) -> bool { |
92 | 18.9M | encode_into(data, may_skip, |s| { |
93 | 18.9M | escaped.push_str(s); |
94 | 18.9M | Ok::<_, std::convert::Infallible>(()) |
95 | 18.9M | }).unwrap() |
96 | 674k | } |
97 | | |
98 | 674k | fn encode_into<E>(mut data: &[u8], may_skip_write: bool, mut push_str: impl FnMut(&str) -> Result<(), E>) -> Result<bool, E> { |
99 | 674k | let mut pushed = false; |
100 | | loop { |
101 | | // Fast path to skip over safe chars at the beginning of the remaining string |
102 | 16.1M | let ascii_len = data.iter() |
103 | 21.1M | .take_while(|&&c| matches!(c, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'-' | b'.' | b'_' | b'~')).count(); |
104 | | |
105 | 16.1M | let (safe, rest) = if ascii_len >= data.len() { |
106 | 674k | if !pushed && may_skip_write { |
107 | 6.04k | return Ok(true); |
108 | 668k | } |
109 | 668k | (data, &[][..]) // redundatnt to optimize out a panic in split_at |
110 | | } else { |
111 | 15.5M | data.split_at(ascii_len) |
112 | | }; |
113 | 16.1M | pushed = true; |
114 | 16.1M | if !safe.is_empty() { |
115 | 3.39M | push_str(unsafe { str::from_utf8_unchecked(safe) })?; |
116 | 12.8M | } |
117 | 16.1M | if rest.is_empty() { |
118 | 668k | break; |
119 | 15.5M | } |
120 | 15.5M | |
121 | 15.5M | match rest.split_first() { |
122 | 15.5M | Some((byte, rest)) => { |
123 | 15.5M | let enc = &[b'%', to_hex_digit(byte >> 4), to_hex_digit(byte & 15)]; |
124 | 15.5M | push_str(unsafe { str::from_utf8_unchecked(enc) })?; |
125 | 15.5M | data = rest; |
126 | | } |
127 | 0 | None => break, |
128 | | }; |
129 | | } |
130 | 668k | Ok(false) |
131 | 674k | } |
132 | | |
133 | | #[inline] |
134 | 31.0M | fn to_hex_digit(digit: u8) -> u8 { |
135 | 31.0M | match digit { |
136 | 31.0M | 0..=9 => b'0' + digit, |
137 | 12.8M | 10..=255 => b'A' - 10 + digit, |
138 | | } |
139 | 31.0M | } |