msg_tool\output_scripts/
po.rs

1//! tools to process gettext po/pot files
2//!
3//! See [spec](https://www.gnu.org/software/gettext/manual/html_node/PO-Files.html)
4use crate::types::*;
5use anyhow::{Result, anyhow};
6use std::collections::HashMap;
7use unicode_segmentation::UnicodeSegmentation;
8
9#[derive(Debug)]
10/// A comment line
11pub enum Comment {
12    /// Translator comment, starting with `# `
13    Translator(String),
14    /// Extracted comment, starting with `#.`.
15    Extracted(String),
16    /// Reference, starting with `#:`.
17    Reference(String),
18    /// Flag, starting with `#,`.
19    Flag(Vec<String>),
20    /// Previous untranslated string, starting with `#|`.
21    Previous(String),
22    /// Previous message block, starting with `#~`.
23    PreviousStr(String),
24}
25
26#[derive(Debug)]
27/// A line in a .po file.
28pub enum PoLine {
29    /// A comment line, starting with `#`.
30    Comment(Comment),
31    /// A msgid line
32    MsgId(String),
33    /// A msgstr line
34    MsgStr(String),
35    /// A msgctxt line
36    MsgCtxt(String),
37    /// A msgid_plural line
38    MsgIdPlural(String),
39    /// A msgstr[n] line
40    MsgStrN(usize, String),
41    /// Empty line
42    EmptyLine,
43}
44
45fn dump_text_in_multi_lines(s: &str) -> Result<String> {
46    if s.contains("\n") {
47        let mut result = Vec::new();
48        result.push("\"\"".to_string());
49        let mut s = s;
50        while let Some(pos) = s.find('\n') {
51            let line = &s[..pos + 1];
52            result.push(format!("\"{}\"", escape_c_str(line)?));
53            s = &s[pos + 1..];
54        }
55        if !s.is_empty() {
56            result.push(format!("\"{}\"", escape_c_str(s)?));
57        }
58        Ok(result.join("\n"))
59    } else {
60        Ok(format!("\"{}\"", escape_c_str(s)?))
61    }
62}
63
64impl PoLine {
65    fn dump(&self) -> Result<String> {
66        Ok(match self {
67            PoLine::Comment(c) => match c {
68                Comment::Translator(s) => format!("# {}", s),
69                Comment::Extracted(s) => format!("#. {}", s),
70                Comment::Reference(s) => format!("#: {}", s),
71                Comment::Flag(flags) => format!("#, {}", flags.join(", ")),
72                Comment::Previous(s) => format!("#| {}", s),
73                Comment::PreviousStr(s) => format!("#~ {}", s),
74            },
75            PoLine::MsgId(s) => format!("msgid {}", dump_text_in_multi_lines(s)?),
76            PoLine::MsgStr(s) => format!("msgstr {}", dump_text_in_multi_lines(s)?),
77            PoLine::MsgCtxt(s) => format!("msgctxt {}", dump_text_in_multi_lines(s)?),
78            PoLine::MsgIdPlural(s) => format!("msgid_plural {}", dump_text_in_multi_lines(s)?),
79            PoLine::MsgStrN(n, s) => format!("msgstr[{}] {}", n, dump_text_in_multi_lines(s)?),
80            PoLine::EmptyLine => String::new(),
81        })
82    }
83}
84
85#[derive(Debug)]
86pub enum MsgStr {
87    Single(String),
88    Plural(Vec<(usize, String)>),
89}
90
91#[derive(Debug)]
92pub struct PoEntry {
93    comments: Vec<Comment>,
94    msgctxt: Option<String>,
95    msgid: String,
96    msgid_plural: Option<String>,
97    msgstr: MsgStr,
98}
99
100/// Escapes a string according to C-style rules.
101///
102/// This function handles common escape sequences like \n, \t, \", \\, etc.
103/// For other ASCII control characters or non-printable characters, it uses octal notation (e.g., \0, \177).
104///
105/// # Arguments
106/// * `s`: The string slice to be escaped.
107///
108/// # Returns
109/// A `Result<String>` containing the new escaped string.
110pub fn escape_c_str(s: &str) -> Result<String> {
111    let mut escaped = String::with_capacity(s.len());
112    for c in s.chars() {
113        match c {
114            '\n' => escaped.push_str("\\n"),
115            '\r' => escaped.push_str("\\r"),
116            '\t' => escaped.push_str("\\t"),
117            '\\' => escaped.push_str("\\\\"),
118            '\"' => escaped.push_str("\\\""),
119            '\0' => escaped.push_str("\\0"),
120            '\x08' => escaped.push_str("\\b"),
121            '\x0c' => escaped.push_str("\\f"),
122            '\x0b' => escaped.push_str("\\v"),
123            '\x07' => escaped.push_str("\\a"),
124            c if c.is_ascii_control() && c != '\n' && c != '\r' && c != '\t' => {
125                escaped.push_str(&format!("\\{:03o}", c as u8));
126            }
127            _ => escaped.push(c),
128        }
129    }
130    Ok(escaped)
131}
132
133/// Unescapes a string that has been escaped C-style.
134///
135/// This function parses common escape sequences (like \n, \t, \", \\) as well as
136/// octal (\ooo) and hexadecimal (\xHH) escape notations.
137///
138/// # Arguments
139/// * `s`: The string slice containing C-style escape sequences.
140///
141/// # Returns
142/// A `Result<String>` containing the new unescaped string.
143/// If an invalid escape sequence is encountered, an error is returned.
144pub fn unescape_c_str(s: &str) -> Result<String> {
145    let mut unescaped = String::with_capacity(s.len());
146    let mut chars = s.chars().peekable();
147
148    while let Some(c) = chars.next() {
149        if c == '\\' {
150            match chars.next() {
151                Some('n') => unescaped.push('\n'),
152                Some('r') => unescaped.push('\r'),
153                Some('t') => unescaped.push('\t'),
154                Some('b') => unescaped.push('\x08'),
155                Some('f') => unescaped.push('\x0c'),
156                Some('v') => unescaped.push('\x0b'),
157                Some('a') => unescaped.push('\x07'),
158                Some('\\') => unescaped.push('\\'),
159                Some('\'') => unescaped.push('\''),
160                Some('\"') => unescaped.push('\"'),
161                Some('?') => unescaped.push('?'),
162                Some(o @ '0'..='7') => {
163                    let mut octal = String::new();
164                    octal.push(o);
165                    while let Some(peek_char) = chars.peek() {
166                        if peek_char.is_digit(8) && octal.len() < 3 {
167                            octal.push(chars.next().unwrap());
168                        } else {
169                            break;
170                        }
171                    }
172                    let value = u8::from_str_radix(&octal, 8).map_err(|e| {
173                        anyhow!("Invalid octal escape sequence: \\{}: {}", octal, e)
174                    })?;
175                    unescaped.push(value as char);
176                }
177                // --- FIX START: Reworked hexadecimal parsing logic ---
178                Some('x') => {
179                    let mut hex = String::new();
180
181                    // Read the first character, which must be a hex digit
182                    if let Some(c1) = chars.peek() {
183                        if c1.is_ascii_hexdigit() {
184                            hex.push(chars.next().unwrap());
185                        } else {
186                            // Handle cases like \xG
187                            return Err(anyhow!(
188                                "Invalid hex escape sequence: \\x followed by non-hex character '{}'",
189                                c1
190                            ));
191                        }
192                    } else {
193                        // Handle cases where \x is at the end of the string
194                        return Err(anyhow!(
195                            "Invalid hex escape sequence: \\x must be followed by a hex digit"
196                        ));
197                    }
198
199                    // Try to read the second character, which must also be a hex digit
200                    if let Some(c2) = chars.peek() {
201                        if c2.is_ascii_hexdigit() {
202                            hex.push(chars.next().unwrap());
203                        } else {
204                            // Handle cases like \xFG
205                            // We have successfully parsed one digit (like F), but it's followed by an invalid hex character (like G)
206                            // As per the test requirements, this should be an error
207                            return Err(anyhow!(
208                                "Invalid hex escape sequence: \\x{} followed by non-hex character '{}'",
209                                hex,
210                                c2
211                            ));
212                        }
213                    }
214
215                    let value =
216                        u8::from_str_radix(&hex, 16).expect("Hex parsing should be valid here");
217                    unescaped.push(value as char);
218                }
219                // --- FIX END ---
220                Some(other) => {
221                    return Err(anyhow!("Unknown escape sequence: \\{}", other));
222                }
223                None => {
224                    return Err(anyhow!("String cannot end with a single backslash"));
225                }
226            }
227        } else {
228            unescaped.push(c);
229        }
230    }
231    Ok(unescaped)
232}
233
234pub struct PoDumper {
235    entries: Vec<PoLine>,
236}
237
238impl PoDumper {
239    pub fn new() -> Self {
240        Self {
241            entries: Vec::new(),
242        }
243    }
244
245    fn gen_start_str(encoding: Encoding) -> String {
246        let mut map = HashMap::new();
247        let content_type = match encoding.charset() {
248            Some(e) => format!("text/plain; charset={}", e),
249            None => String::from("text/plain"),
250        };
251        map.insert("Content-Type", content_type);
252        map.insert("X-Generator", String::from("msg-tool"));
253        map.insert("MIME-Version", String::from("1.0"));
254        let mut result = String::new();
255        for (k, v) in map {
256            result.push_str(&format!("{}: {}\n", k, v));
257        }
258        result
259    }
260
261    pub fn dump(mut self, entries: &[Message], encoding: Encoding) -> Result<String> {
262        self.add_entry(PoEntry {
263            comments: vec![
264                Comment::Translator(String::from("Generated by msg-tool")),
265                Comment::Flag(vec![String::from("fuzzy")]),
266            ],
267            msgctxt: None,
268            msgid: String::new(),
269            msgid_plural: None,
270            msgstr: MsgStr::Single(Self::gen_start_str(encoding)),
271        });
272        let mut added_messages: HashMap<&String, usize> = HashMap::new();
273        for entry in entries {
274            let count = added_messages.get(&entry.message).map(|&s| s).unwrap_or(0);
275            self.add_entry(PoEntry {
276                comments: entry
277                    .name
278                    .as_ref()
279                    .map(|name| vec![Comment::Translator(format!("NAME: {}", name))])
280                    .unwrap_or_default(),
281                msgctxt: if count > 0 {
282                    Some(format!("{}", count))
283                } else {
284                    None
285                },
286                msgid: entry.message.clone(),
287                msgid_plural: None,
288                msgstr: MsgStr::Single(String::new()),
289            });
290            added_messages.insert(&entry.message, count + 1);
291        }
292        let mut result = String::new();
293        for line in &self.entries {
294            result.push_str(&line.dump()?);
295            result.push('\n');
296        }
297        Ok(result)
298    }
299
300    fn add_entry(&mut self, entry: PoEntry) {
301        for comment in entry.comments {
302            self.entries.push(PoLine::Comment(comment));
303        }
304        if let Some(ctx) = entry.msgctxt {
305            self.entries.push(PoLine::MsgCtxt(ctx));
306        }
307        self.entries.push(PoLine::MsgId(entry.msgid));
308        let is_plural = entry.msgid_plural.is_some();
309        if let Some(plural) = entry.msgid_plural {
310            self.entries.push(PoLine::MsgIdPlural(plural));
311        }
312        match entry.msgstr {
313            MsgStr::Single(s) => {
314                if is_plural {
315                    self.entries.push(PoLine::MsgStrN(0, s));
316                } else {
317                    self.entries.push(PoLine::MsgStr(s));
318                }
319            }
320            MsgStr::Plural(v) => {
321                for (n, s) in v {
322                    self.entries.push(PoLine::MsgStrN(n, s));
323                }
324            }
325        }
326        self.entries.push(PoLine::EmptyLine);
327    }
328}
329
330pub struct PoParser<'a> {
331    texts: Vec<&'a str>,
332    pos: usize,
333    llm_mark: Option<&'a str>,
334}
335
336impl<'a> PoParser<'a> {
337    pub fn new(s: &'a str, llm_mark: Option<&'a str>) -> Self {
338        Self {
339            texts: s.graphemes(true).collect(),
340            pos: 0,
341            llm_mark,
342        }
343    }
344
345    pub fn parse_lines(&mut self) -> Result<Vec<PoLine>> {
346        let mut lines = Vec::new();
347        while let Some(f) = self.next_line() {
348            let f = f.trim();
349            if f.starts_with("#") {
350                if f.len() < 2 {
351                    return Err(anyhow!("Invalid comment line: {}", f));
352                }
353                let c = &f[1..];
354                if c.starts_with(' ') {
355                    lines.push(PoLine::Comment(Comment::Translator(c[1..].to_string())));
356                } else if c.starts_with('.') {
357                    lines.push(PoLine::Comment(Comment::Extracted(
358                        c[1..].trim_start().to_string(),
359                    )));
360                } else if c.starts_with(':') {
361                    lines.push(PoLine::Comment(Comment::Reference(
362                        c[1..].trim_start().to_string(),
363                    )));
364                } else if c.starts_with(',') {
365                    let flags = c[1..].split(',').map(|s| s.trim().to_string()).collect();
366                    lines.push(PoLine::Comment(Comment::Flag(flags)));
367                } else if c.starts_with('|') {
368                    lines.push(PoLine::Comment(Comment::Previous(
369                        c[1..].trim_start().to_string(),
370                    )));
371                } else if c.starts_with('~') {
372                    lines.push(PoLine::Comment(Comment::PreviousStr(
373                        c[1..].trim_start().to_string(),
374                    )));
375                } else {
376                    return Err(anyhow!("Unknown comment type: {}", f));
377                }
378            } else if f.starts_with("msgid ") {
379                let content = self.read_string_literal(&f[6..])?;
380                lines.push(PoLine::MsgId(content));
381            } else if f.starts_with("msgstr ") {
382                let content = self.read_string_literal(&f[7..])?;
383                lines.push(PoLine::MsgStr(content));
384            } else if f.starts_with("msgctxt ") {
385                let content = self.read_string_literal(&f[8..])?;
386                lines.push(PoLine::MsgCtxt(content));
387            } else if f.starts_with("msgid_plural ") {
388                let content = self.read_string_literal(&f[13..])?;
389                lines.push(PoLine::MsgIdPlural(content));
390            } else if f.starts_with("msgstr[") {
391                let end_bracket = f
392                    .find(']')
393                    .ok_or_else(|| anyhow!("Invalid msgstr[n] line: {}", f))?;
394                let index_str = &f[7..end_bracket];
395                let index: usize = index_str
396                    .parse()
397                    .map_err(|_| anyhow!("Invalid index in msgstr[n]: {}", index_str))?;
398                let content = self.read_string_literal(&f[end_bracket + 1..])?;
399                lines.push(PoLine::MsgStrN(index, content));
400            } else if f.trim().is_empty() {
401                lines.push(PoLine::EmptyLine);
402            } else if f.starts_with('"') {
403                // This is a continuation of a previous string.
404                // According to GNU gettext manual, a string literal cannot appear on its own.
405                // It must follow a keyword. However, some tools generate this.
406                // We will append it to the last string-like element.
407                let content = self.read_string_literal(&f)?;
408                if let Some(last_line) = lines.last_mut() {
409                    match last_line {
410                        PoLine::MsgId(s) => s.push_str(&content),
411                        PoLine::MsgStr(s) => s.push_str(&content),
412                        PoLine::MsgCtxt(s) => s.push_str(&content),
413                        PoLine::MsgIdPlural(s) => s.push_str(&content),
414                        PoLine::MsgStrN(_, s) => s.push_str(&content),
415                        _ => return Err(anyhow!("Orphan string literal continuation: {}", f)),
416                    }
417                } else {
418                    return Err(anyhow!("Orphan string literal continuation: {}", f));
419                }
420            } else {
421                return Err(anyhow!("Unknown line type: {}", f));
422            }
423        }
424        Ok(lines)
425    }
426
427    fn read_string_literal(&mut self, s: &str) -> Result<String> {
428        let mut content = String::new();
429        let current_line_str = s.trim();
430        if current_line_str.starts_with('"') && current_line_str.ends_with('"') {
431            content.push_str(&unescape_c_str(
432                &current_line_str[1..current_line_str.len() - 1],
433            )?);
434        } else {
435            return Err(anyhow!("Invalid string literal: {}", s));
436        }
437
438        while let Some(peeked_line) = self.peek_line() {
439            if peeked_line.trim().starts_with('"') {
440                self.next_line(); // consume it
441                let trimmed_line = peeked_line.trim();
442                if trimmed_line.starts_with('"') && trimmed_line.ends_with('"') {
443                    content.push_str(&unescape_c_str(&trimmed_line[1..trimmed_line.len() - 1])?);
444                } else {
445                    return Err(anyhow!(
446                        "Invalid string literal continuation: {}",
447                        peeked_line
448                    ));
449                }
450            } else {
451                break;
452            }
453        }
454        Ok(content)
455    }
456
457    pub fn parse_entries(&mut self) -> Result<Vec<PoEntry>> {
458        let lines = self.parse_lines()?;
459        let mut entries = Vec::new();
460        let mut current_entry_lines: Vec<PoLine> = Vec::new();
461
462        for line in lines {
463            if let PoLine::EmptyLine = line {
464                if !current_entry_lines.is_empty() {
465                    entries.push(self.build_entry_from_lines(current_entry_lines)?);
466                    current_entry_lines = Vec::new();
467                }
468            } else {
469                current_entry_lines.push(line);
470            }
471        }
472
473        if !current_entry_lines.is_empty() {
474            entries.push(self.build_entry_from_lines(current_entry_lines)?);
475        }
476
477        Ok(entries)
478    }
479
480    fn build_entry_from_lines(&self, lines: Vec<PoLine>) -> Result<PoEntry> {
481        let mut comments = Vec::new();
482        let mut msgctxt: Option<String> = None;
483        let mut msgid: Option<String> = None;
484        let mut msgid_plural: Option<String> = None;
485        let mut msgstr: Option<String> = None;
486        let mut msgstr_plural: Vec<(usize, String)> = Vec::new();
487
488        for line in lines {
489            match line {
490                PoLine::Comment(c) => comments.push(c),
491                PoLine::MsgCtxt(s) => {
492                    if msgctxt.is_some() {
493                        return Err(anyhow!("Duplicate msgctxt in entry"));
494                    }
495                    msgctxt = Some(s);
496                }
497                PoLine::MsgId(s) => {
498                    if msgid.is_some() {
499                        return Err(anyhow!("Duplicate msgid in entry"));
500                    }
501                    msgid = Some(s);
502                }
503                PoLine::MsgIdPlural(s) => {
504                    if msgid_plural.is_some() {
505                        return Err(anyhow!("Duplicate msgid_plural in entry"));
506                    }
507                    msgid_plural = Some(s);
508                }
509                PoLine::MsgStr(s) => {
510                    if msgstr.is_some() {
511                        return Err(anyhow!("Duplicate msgstr in entry"));
512                    }
513                    msgstr = Some(s);
514                }
515                PoLine::MsgStrN(n, s) => {
516                    if msgstr_plural.iter().any(|(i, _)| *i == n) {
517                        return Err(anyhow!("Duplicate msgstr[{}] in entry", n));
518                    }
519                    msgstr_plural.push((n, s));
520                }
521                PoLine::EmptyLine => {
522                    // This should not be reached if called from parse_entries
523                    return Err(anyhow!("Unexpected empty line in build_entry_from_lines"));
524                }
525            }
526        }
527
528        let final_msgstr = if !msgstr_plural.is_empty() {
529            if msgstr.is_some() {
530                return Err(anyhow!(
531                    "Mixing msgstr and msgstr[n] in the same entry is not allowed"
532                ));
533            }
534            MsgStr::Plural(msgstr_plural)
535        } else {
536            MsgStr::Single(msgstr.unwrap_or_default())
537        };
538
539        Ok(PoEntry {
540            comments,
541            msgctxt,
542            msgid: msgid.ok_or_else(|| anyhow!("Entry is missing msgid"))?,
543            msgid_plural,
544            msgstr: final_msgstr,
545        })
546    }
547
548    fn peek(&self) -> Option<&'a str> {
549        self.texts.get(self.pos).copied()
550    }
551
552    fn peek_line(&self) -> Option<String> {
553        let mut line = String::new();
554        let mut current_pos = self.pos;
555        while let Some(c) = self.texts.get(current_pos).copied() {
556            current_pos += 1;
557            if c == "\n" || c == "\r\n" {
558                break;
559            }
560            line.push_str(c);
561        }
562        if line.is_empty() && current_pos >= self.texts.len() {
563            None
564        } else {
565            Some(line)
566        }
567    }
568
569    fn next_line(&mut self) -> Option<String> {
570        let mut line = String::new();
571        while let Some(c) = self.next() {
572            if c == "\n" || c == "\r\n" {
573                break;
574            }
575            line.push_str(c);
576        }
577        if line.is_empty() && self.peek().is_none() {
578            None
579        } else {
580            Some(line)
581        }
582    }
583
584    fn next(&mut self) -> Option<&'a str> {
585        let r = self.texts.get(self.pos).copied();
586        if r.is_some() {
587            self.pos += 1;
588        }
589        r
590    }
591
592    pub fn parse_as_vec(&mut self) -> Result<Vec<(String, String)>> {
593        let mut map = Vec::new();
594        let mut llm = None;
595        for (i, entry) in self.parse_entries()?.into_iter().enumerate() {
596            if entry.msgid.is_empty() && i == 0 {
597                // This is the header entry, skip it
598                continue;
599            }
600            for comment in &entry.comments {
601                if let Comment::Translator(s) = comment {
602                    let s = s.trim();
603                    if s.starts_with("NAME:") {
604                        // name = Some(s[5..].trim().to_string());
605                    } else if s.starts_with("LLM:") {
606                        llm = Some(s[4..].trim().replace("\\n", "\n"));
607                    }
608                }
609            }
610            let message = match entry.msgstr {
611                MsgStr::Single(s) => {
612                    let s = s.trim();
613                    if s.is_empty() {
614                        llm.take()
615                            .map(|mut llm| {
616                                if let Some(mark) = self.llm_mark {
617                                    llm.push_str(mark);
618                                }
619                                llm
620                            })
621                            .unwrap_or_else(|| {
622                                String::from(if entry.msgid.is_empty() { "" } else { "" })
623                            })
624                    } else {
625                        let mut tmp = s.to_string();
626                        if let Some(llm) = llm.take() {
627                            if tmp == llm {
628                                if let Some(mark) = self.llm_mark {
629                                    tmp.push_str(mark);
630                                }
631                            }
632                        }
633                        tmp
634                    }
635                }
636                MsgStr::Plural(_) => {
637                    return Err(anyhow!("Plural msgstr not supported in this context"));
638                }
639            };
640            map.push((entry.msgid, message));
641        }
642        Ok(map)
643    }
644
645    pub fn parse(&mut self) -> Result<Vec<Message>> {
646        let mut messages = Vec::new();
647        let mut llm = None;
648        let mut name = None;
649        for (i, entry) in self.parse_entries()?.into_iter().enumerate() {
650            if entry.msgid.is_empty() && i == 0 {
651                // This is the header entry, skip it
652                continue;
653            }
654            for comment in &entry.comments {
655                if let Comment::Translator(s) = comment {
656                    let s = s.trim();
657                    if s.starts_with("NAME:") {
658                        name = Some(s[5..].trim().to_string());
659                    } else if s.starts_with("LLM:") {
660                        llm = Some(s[4..].trim().replace("\\n", "\n"));
661                    }
662                }
663            }
664            let message = match entry.msgstr {
665                MsgStr::Single(s) => {
666                    let s = s.trim();
667                    if s.is_empty() {
668                        llm.take()
669                            .map(|mut llm| {
670                                if let Some(mark) = self.llm_mark {
671                                    llm.push_str(mark);
672                                }
673                                llm
674                            })
675                            .unwrap_or_else(|| {
676                                String::from(if entry.msgid.is_empty() { "" } else { "" })
677                            })
678                    } else {
679                        let mut tmp = s.to_string();
680                        if let Some(llm) = llm.take() {
681                            if tmp == llm {
682                                if let Some(mark) = self.llm_mark {
683                                    tmp.push_str(mark);
684                                }
685                            }
686                        }
687                        tmp
688                    }
689                }
690                MsgStr::Plural(_) => {
691                    return Err(anyhow!("Plural msgstr not supported in this context"));
692                }
693            };
694            let m = Message::new(message, name.take());
695            messages.push(m);
696        }
697        Ok(messages)
698    }
699}
700
701// --- Unit Tests ---
702#[cfg(test)]
703mod c_escape_tests {
704    use super::*;
705
706    #[test]
707    fn test_escape_basic() {
708        assert_eq!(escape_c_str("hello world").unwrap(), "hello world");
709    }
710
711    #[test]
712    fn test_escape_quotes_and_slashes() {
713        assert_eq!(
714            escape_c_str(r#"he"llo\world"#).unwrap(),
715            r#"he\"llo\\world"#
716        );
717    }
718
719    #[test]
720    fn test_escape_control_chars() {
721        assert_eq!(escape_c_str("a\nb\tc\rd").unwrap(), r#"a\nb\tc\rd"#);
722        assert_eq!(escape_c_str("\0").unwrap(), r#"\0"#);
723    }
724
725    #[test]
726    fn test_escape_other_control_chars_as_octal() {
727        assert_eq!(escape_c_str("\x07").unwrap(), r#"\a"#);
728        assert_eq!(escape_c_str("\x7f").unwrap(), r#"\177"#);
729    }
730
731    #[test]
732    fn test_unescape_basic() {
733        assert_eq!(unescape_c_str("hello world").unwrap(), "hello world");
734    }
735
736    #[test]
737    fn test_unescape_quotes_and_slashes() {
738        assert_eq!(
739            unescape_c_str(r#"he\"llo\\world"#).unwrap(),
740            r#"he"llo\world"#
741        );
742    }
743
744    #[test]
745    fn test_unescape_control_chars() {
746        assert_eq!(unescape_c_str(r#"a\nb\tc\rd"#).unwrap(), "a\nb\tc\rd");
747    }
748
749    #[test]
750    fn test_unescape_octal() {
751        assert_eq!(unescape_c_str(r#"\101"#).unwrap(), "A");
752        assert_eq!(unescape_c_str(r#"\60"#).unwrap(), "0");
753        assert_eq!(unescape_c_str(r#"\0"#).unwrap(), "\0");
754        assert_eq!(unescape_c_str(r#"\177"#).unwrap(), "\x7f");
755        assert_eq!(unescape_c_str(r#"hello\101world"#).unwrap(), "helloAworld");
756    }
757
758    #[test]
759    fn test_unescape_hex() {
760        assert_eq!(unescape_c_str(r#"\x41"#).unwrap(), "A");
761        assert_eq!(unescape_c_str(r#"\x30"#).unwrap(), "0");
762        assert_eq!(unescape_c_str(r#"\x7F"#).unwrap(), "\x7f");
763        assert_eq!(unescape_c_str(r#"\x7f"#).unwrap(), "\x7f");
764        assert_eq!(unescape_c_str(r#"hello\x41world"#).unwrap(), "helloAworld");
765        // A single hex digit is also valid
766        assert_eq!(unescape_c_str(r#"\xF"#).unwrap(), "\x0f");
767    }
768
769    #[test]
770    fn test_unescape_mixed() {
771        let original = "A\tB\"C\\D\0E";
772        let escaped = r#"A\tB\"C\\D\0E"#;
773        assert_eq!(unescape_c_str(escaped).unwrap(), original);
774    }
775
776    #[test]
777    fn test_unescape_invalid_sequence() {
778        assert!(unescape_c_str(r#"\q"#).is_err());
779        assert!(unescape_c_str(r#"hello\"#).is_err());
780        assert!(unescape_c_str(r#"\x"#).is_err());
781        // New: test \x followed immediately by an invalid character
782        assert!(unescape_c_str(r#"\xG"#).is_err());
783        // This should now pass
784        assert!(unescape_c_str(r#"\xFG"#).is_err());
785        assert!(unescape_c_str(r#"\8"#).is_err());
786    }
787}