1use serde::Serialize;
2use std::fs::File;
3use std::io::{self, BufRead};
4use std::path::Path;
5
6pub fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
12where
13 P: AsRef<Path>,
14{
15 let file = File::open(filename)?;
16 Ok(io::BufReader::new(file).lines())
17}
18#[must_use]
21pub fn to_unicode(domain: &str) -> (String, String) {
22 match idna::domain_to_unicode(domain) {
23 (s, Err(e)) => (s, e.to_string()),
24 (s, _) => (s, String::new()),
25 }
26}
27
28#[must_use]
29pub fn to_ascii(domain: &str) -> (String, String) {
30 match idna::domain_to_ascii(domain) {
31 Ok(s) => (s, String::new()),
32 Err(e) => (String::new(), e.to_string()),
33 }
34}
35
36#[must_use]
37pub fn process(domain: &str, decode: bool) -> (String, String) {
38 if decode {
39 to_unicode(domain)
40 } else {
41 to_ascii(domain)
42 }
43}
44
45pub fn print_csv_result(domain: &str, decode: bool) {
46 let (converted, errors) = process(domain, decode);
47 println!("{domain:?},{converted:?},{errors:?}");
48}
49
50#[derive(Debug, Serialize)]
51pub struct Domain {
52 ascii: String,
53 unicode: String,
54 errors: String,
55}
56
57impl Domain {
58 #[must_use]
59 pub fn new(domain: &str, decode: bool) -> Domain {
60 let (converted, errors) = process(domain, decode);
61 if decode {
62 Domain {
63 ascii: domain.to_string(),
64 unicode: converted,
65 errors,
66 }
67 } else {
68 Domain {
69 ascii: converted,
70 unicode: domain.to_string(),
71 errors,
72 }
73 }
74 }
75}