Parse IPv6 address string to 16-byte array
(addr_str: &str)
| 868 | |
| 869 | /// Parse IPv6 address string to 16-byte array |
| 870 | fn parse_ipv6(addr_str: &str) -> Result<[u8; 16], String> { |
| 871 | // Simple IPv6 parsing - for production, consider using a proper library |
| 872 | let addr_str = addr_str.trim(); |
| 873 | |
| 874 | // Handle special cases |
| 875 | if addr_str == "::" { |
| 876 | return Ok([0u8; 16]); |
| 877 | } |
| 878 | |
| 879 | // Handle IPv6 address expansion for "::" compression |
| 880 | let (left, right) = if let Some(pos) = addr_str.find("::") { |
| 881 | let left_part = &addr_str[..pos]; |
| 882 | let right_part = &addr_str[pos + 2..]; |
| 883 | (left_part, right_part) |
| 884 | } else { |
| 885 | (addr_str, "") |
| 886 | }; |
| 887 | |
| 888 | let mut result = [0u8; 16]; |
| 889 | let mut pos = 0; |
| 890 | |
| 891 | // Parse left part |
| 892 | if !left.is_empty() { |
| 893 | for group in left.split(':') { |
| 894 | if group.is_empty() { |
| 895 | continue; |
| 896 | } |
| 897 | let value = u16::from_str_radix(group, 16) |
| 898 | .map_err(|_| format!("Invalid IPv6 group: {group}"))?; |
| 899 | result[pos] = (value >> 8) as u8; |
| 900 | result[pos + 1] = (value & 0xFF) as u8; |
| 901 | pos += 2; |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | // Parse right part (if any) |
| 906 | if !right.is_empty() { |
| 907 | let mut right_groups = Vec::new(); |
| 908 | for group in right.split(':') { |
| 909 | if group.is_empty() { |
| 910 | continue; |
| 911 | } |
| 912 | let value = u16::from_str_radix(group, 16) |
| 913 | .map_err(|_| format!("Invalid IPv6 group: {group}"))?; |
| 914 | right_groups.push(value); |
| 915 | } |
| 916 | |
| 917 | // Place right groups at the end |
| 918 | let mut right_pos = 16 - (right_groups.len() * 2); |
| 919 | for value in right_groups { |
| 920 | result[right_pos] = (value >> 8) as u8; |
| 921 | result[right_pos + 1] = (value & 0xFF) as u8; |
| 922 | right_pos += 2; |
| 923 | } |
| 924 | } |
| 925 | |
| 926 | Ok(result) |
| 927 | } |