truecalc_core/eval/functions/web/encodeurl/
mod.rs1use crate::eval::coercion::to_string_val;
2use crate::eval::functions::check_arity;
3use crate::types::Value;
4
5pub fn encodeurl_fn(args: &[Value]) -> Value {
10 if let Some(err) = check_arity(args, 1, 1) {
11 return err;
12 }
13 let text = match to_string_val(args[0].clone()) {
14 Ok(s) => s,
15 Err(e) => return e,
16 };
17 Value::Text(percent_encode(&text))
18}
19
20fn percent_encode(s: &str) -> String {
21 let mut out = String::with_capacity(s.len());
22 for byte in s.bytes() {
23 match byte {
24 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'
25 | b'-' | b'_' | b'.' | b'~' => {
26 out.push(byte as char);
27 }
28 _ => {
29 out.push('%');
30 out.push(hex_digit(byte >> 4));
31 out.push(hex_digit(byte & 0x0f));
32 }
33 }
34 }
35 out
36}
37
38fn hex_digit(n: u8) -> char {
39 match n {
40 0..=9 => (b'0' + n) as char,
41 _ => (b'A' + n - 10) as char,
42 }
43}
44
45#[cfg(test)]
46mod tests;