|
| 1 | +use crate::compiler::prelude::*; |
| 2 | + |
| 3 | +#[derive(Clone, Copy, Debug)] |
| 4 | +pub struct EncodePunycode; |
| 5 | + |
| 6 | +impl Function for EncodePunycode { |
| 7 | + fn identifier(&self) -> &'static str { |
| 8 | + "encode_punycode" |
| 9 | + } |
| 10 | + |
| 11 | + fn parameters(&self) -> &'static [Parameter] { |
| 12 | + &[Parameter { |
| 13 | + keyword: "value", |
| 14 | + kind: kind::BYTES, |
| 15 | + required: true, |
| 16 | + }] |
| 17 | + } |
| 18 | + |
| 19 | + fn compile( |
| 20 | + &self, |
| 21 | + _state: &state::TypeState, |
| 22 | + _ctx: &mut FunctionCompileContext, |
| 23 | + arguments: ArgumentList, |
| 24 | + ) -> Compiled { |
| 25 | + let value = arguments.required("value"); |
| 26 | + |
| 27 | + Ok(EncodePunycodeFn { value }.as_expr()) |
| 28 | + } |
| 29 | + |
| 30 | + fn examples(&self) -> &'static [Example] { |
| 31 | + &[ |
| 32 | + Example { |
| 33 | + title: "IDN string", |
| 34 | + source: r#"encode_punycode!("www.café.com")"#, |
| 35 | + result: Ok("www.xn--caf-dma.com"), |
| 36 | + }, |
| 37 | + Example { |
| 38 | + title: "mixed case string", |
| 39 | + source: r#"encode_punycode!("www.CAFé.com")"#, |
| 40 | + result: Ok("www.xn--caf-dma.com"), |
| 41 | + }, |
| 42 | + Example { |
| 43 | + title: "ascii string", |
| 44 | + source: r#"encode_punycode!("www.cafe.com")"#, |
| 45 | + result: Ok("www.cafe.com"), |
| 46 | + }, |
| 47 | + ] |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +#[derive(Clone, Debug)] |
| 52 | +struct EncodePunycodeFn { |
| 53 | + value: Box<dyn Expression>, |
| 54 | +} |
| 55 | + |
| 56 | +impl FunctionExpression for EncodePunycodeFn { |
| 57 | + fn resolve(&self, ctx: &mut Context) -> Resolved { |
| 58 | + let value = self.value.resolve(ctx)?; |
| 59 | + let string = value.try_bytes_utf8_lossy()?; |
| 60 | + |
| 61 | + let encoded = idna::domain_to_ascii(&string) |
| 62 | + .map_err(|errors| format!("unable to encode to punycode: {errors}"))?; |
| 63 | + |
| 64 | + Ok(encoded.into()) |
| 65 | + } |
| 66 | + |
| 67 | + fn type_def(&self, _: &state::TypeState) -> TypeDef { |
| 68 | + TypeDef::bytes().fallible() |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +#[cfg(test)] |
| 73 | +mod test { |
| 74 | + use super::*; |
| 75 | + use crate::value; |
| 76 | + |
| 77 | + test_function![ |
| 78 | + encode_punycode => EncodePunycode; |
| 79 | + |
| 80 | + idn_string { |
| 81 | + args: func_args![value: value!("www.café.com")], |
| 82 | + want: Ok(value!("www.xn--caf-dma.com")), |
| 83 | + tdef: TypeDef::bytes().fallible(), |
| 84 | + } |
| 85 | + |
| 86 | + mixed_case { |
| 87 | + args: func_args![value: value!("www.CAFé.com")], |
| 88 | + want: Ok(value!("www.xn--caf-dma.com")), |
| 89 | + tdef: TypeDef::bytes().fallible(), |
| 90 | + } |
| 91 | + |
| 92 | + ascii_string { |
| 93 | + args: func_args![value: value!("www.cafe.com")], |
| 94 | + want: Ok(value!("www.cafe.com")), |
| 95 | + tdef: TypeDef::bytes().fallible(), |
| 96 | + } |
| 97 | + ]; |
| 98 | +} |
0 commit comments