1use crate::compiler::prelude::*;
2use bytes::Bytes;
3use std::net::IpAddr;
4
5fn ip_pton(value: &Value) -> Resolved {
6 let ip: IpAddr = value
7 .try_bytes_utf8_lossy()?
8 .parse()
9 .map_err(|err| format!("unable to parse IP address: {err}"))?;
10
11 let bytes = match ip {
12 IpAddr::V4(ipv4) => Bytes::copy_from_slice(&ipv4.octets()),
13 IpAddr::V6(ipv6) => Bytes::copy_from_slice(&ipv6.octets()),
14 };
15
16 Ok(bytes.into())
17}
18
19#[derive(Clone, Copy, Debug)]
20pub struct IpPton;
21
22impl Function for IpPton {
23 fn identifier(&self) -> &'static str {
24 "ip_pton"
25 }
26
27 fn usage(&self) -> &'static str {
28 indoc! {"
29 Converts IPv4 and IPv6 addresses from text to binary form.
30
31 * The binary form of IPv4 addresses is 4 bytes (32 bits) long.
32 * The binary form of IPv6 addresses is 16 bytes (128 bits) long.
33
34 This behavior mimics [inet_pton](https://linux.die.net/man/3/inet_pton).
35 "}
36 }
37
38 fn category(&self) -> &'static str {
39 Category::Ip.as_ref()
40 }
41
42 fn internal_failure_reasons(&self) -> &'static [&'static str] {
43 &["`value` is not a valid IP (v4 or v6) address in text form."]
44 }
45
46 fn return_kind(&self) -> u16 {
47 kind::BYTES
48 }
49
50 fn notices(&self) -> &'static [&'static str] {
51 &[indoc! {"
52 The binary data from this function is not easily printable. However, functions such as
53 `encode_base64` or `encode_percent` can still process it correctly.
54 "}]
55 }
56
57 fn parameters(&self) -> &'static [Parameter] {
58 const PARAMETERS: &[Parameter] = &[Parameter::required(
59 "value",
60 kind::BYTES,
61 "The IP address (v4 or v6) to convert to binary form.",
62 )];
63 PARAMETERS
64 }
65
66 fn examples(&self) -> &'static [Example] {
67 &[
68 example! {
69 title: "Convert IPv4 address to bytes and encode to Base64",
70 source: r#"encode_base64(ip_pton!("192.168.0.1"))"#,
71 result: Ok("wKgAAQ=="),
72 },
73 example! {
74 title: "Convert IPv6 address to bytes and encode to Base64",
75 source: r#"encode_base64(ip_pton!("2001:db8:85a3::8a2e:370:7334"))"#,
76 result: Ok("IAENuIWjAAAAAIouA3BzNA=="),
77 },
78 ]
79 }
80
81 fn compile(
82 &self,
83 _state: &state::TypeState,
84 _ctx: &mut FunctionCompileContext,
85 arguments: ArgumentList,
86 ) -> Compiled {
87 let value = arguments.required("value");
88
89 Ok(IpPtonFn { value }.as_expr())
90 }
91}
92
93#[derive(Debug, Clone)]
94struct IpPtonFn {
95 value: Box<dyn Expression>,
96}
97
98impl FunctionExpression for IpPtonFn {
99 fn resolve(&self, ctx: &mut Context) -> Resolved {
100 let value = self.value.resolve(ctx)?;
101 ip_pton(&value)
102 }
103
104 fn type_def(&self, _: &state::TypeState) -> TypeDef {
105 TypeDef::bytes().fallible()
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112 use crate::value;
113
114 test_function![
115 ip_pton => IpPton;
116
117 invalid {
118 args: func_args![value: "i am not an ipaddress"],
119 want: Err("unable to parse IP address: invalid IP address syntax"),
120 tdef: TypeDef::bytes().fallible(),
121 }
122
123 valid_ipv4 {
124 args: func_args![value: "1.2.3.4"],
125 want: Ok(value!("\x01\x02\x03\x04")),
126 tdef: TypeDef::bytes().fallible(),
127 }
128
129 valid_ipv6 {
130 args: func_args![value: "102:304:506:708:90a:b0c:d0e:f10"],
131 want: Ok(value!("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10")),
132 tdef: TypeDef::bytes().fallible(),
133 }
134 ];
135}