### Example: escape and unescape functions Source: https://docs.rs/escape8259 Shows how to use the escape and unescape functions from the escape8259 crate. The example demonstrates escaping a string with a null character and a double quote, unescaping a Unicode escape sequence for a crab emoji, handling unnecessary encodings, and escaping a multiline string. ```rust use escape8259::{escape, unescape}; let s = "A null (\0) and a double-quote (\")"; assert_eq!(escape(s), r#"A null (\u0000) and a double-quote (\")"#); let crab = r#"This is a crab: \ud83e\udd80"#; assert_eq!(unescape(crab).unwrap(), "This is a crab: πŸ¦€"); // We accept encodings that weren't really necessary. assert_eq!(unescape(r#"\u0041\n"#).unwrap(), "A\n"); let multiline = r#"hello world"#; assert_eq!(escape(multiline), r#"hello\n world"#); ``` -------------------------------- ### Unescape with unescape, unescape_str, and unescape_string Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Inside a test function, unescape three different escaped strings using the unescape, unescape_str, and unescape_string functions, then assert each result equals the original string s. ```rust let unescaped1 = unescape(&escaped1).unwrap(); let unescaped2 = unescape_str(&escaped2).unwrap(); let unescaped3 = unescape_string(escaped3).unwrap(); assert_eq!(s, unescaped1); assert_eq!(s, unescaped2); assert_eq!(s, unescaped3); ``` -------------------------------- ### escape Source: https://docs.rs/escape8259/latest/escape8259/fn.escape.html?search=u32+-%3E+bool Documentation for the escape function from the escape8259 crate. ```APIDOC ## Function escape ### Description Escapes a string following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark `?`, reverse solidus `\` (backslash), and the control characters (`0x00-1F`). ### Signature ```rust pub fn escape(s: S) -> String where S: AsRef, ``` ### Parameters - **s** (S) - Required - The string to escape. Must implement `AsRef`. ### Return Value - **String** - The escaped string. ### Notes If performance is important, and it’s likely that the input string will not require any escaping, perhaps consider using `escape_str` or `escape_string` instead. ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/escape8259/fn.escape_str.html?search=std%3A%3Avec Documentation for the `escape_str` function from the `escape8259` crate. ```APIDOC ## escape_str ### Description Escapes a `&str` following RFC8259 rules. Only characters that require escaping are escaped: quotation mark `?`, reverse solidus `\` (backslash), and control characters (`0x00-1F`). This function may be faster than `escape` if no escaping is needed, as it can return the input without performing any heap allocations. ### Signature ```rust pub fn escape_str<'a>(s: &'a str) -> Cow<'a, str> ``` ### Parameters - `s` (`&'a str`) - The input string to escape. ### Returns - `Cow<'a, str>` - The escaped string, either borrowed if no escaping is needed, or owned if escaping was performed. ``` -------------------------------- ### UnescapeState struct and methods Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Internal state machine for collecting output characters and queuing UTF-16 words during unescaping. Includes constructors, push_char, push_u16, and finalize methods. ```rust struct UnescapeState { // The accumulated characters out: String, // Store a fragment of a large character for later decoding stash: u16, } impl UnescapeState { fn new() -> UnescapeState { UnescapeState { out: String::new(), stash: 0, } } fn from_str(init: &str) -> UnescapeState { UnescapeState { out: init.to_owned(), stash: 0, } } // Collect a new character fn push_char(&mut self, c: char) -> UnescapeResult<()> { if self.stash != 0 { return Err(UnescapeError {}); } self.out.push(c); Ok(()) } // Collect a new UTF16 word. This can either be one whole character, // or part of a larger character. fn push_u16(&mut self, x: u16) -> UnescapeResult<()> { let surrogate = (0xD800..=0xDFFF).contains(&x); match (self.stash, surrogate) { (0, false) => { // The std library only provides utf16 decode of an iterator, // so to decode a single character we wrap it in an array. // Hopefully the compiler will elide most of this extra work. let words = [x]; match decode_utf16(words.iter().copied()).next() { Some(Ok(c)) => { self.out.push(c); } _ => return Err(UnescapeError {}), } } (0, true) => self.stash = x, (_, false) => { return Err(UnescapeError {}); } (w, true) => { let words = [w, x]; match decode_utf16(words.iter().copied()).next() { Some(Ok(c)) => { self.out.push(c); self.stash = 0; } _ => return Err(UnescapeError {}), } } } Ok(()) } // If we queued up part of a UTF-16 encoded word but didn't // finish it, return an error. Otherwise, consume self and // return the accumulated String. fn finalize(self) -> UnescapeResult { if self.stash != 0 { return Err(UnescapeError {}); } Ok(self.out) } } ``` -------------------------------- ### unescape: Unescape any AsRef Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Unescapes a string following RFC8259 rules. Accepts any type that implements AsRef. Always returns an owned String, even if no unescaping is needed. ```rust pub fn unescape(s: S) -> UnescapeResult where S: AsRef, { let state = UnescapeState::new(); unescape_inner(state, s.as_ref()) } ``` -------------------------------- ### escape_string Source: https://docs.rs/escape8259/latest/escape8259/all.html?search= Escapes a string and returns the escaped string. This is a convenience wrapper around the escape function. ```APIDOC ## escape_string ### Description Escapes a string and returns the escaped string. ### Function `escape_string` ### Parameters - **input** (string) - Required - The string to escape. ### Returns - **String** - The escaped string. ``` -------------------------------- ### unescape Source: https://docs.rs/escape8259/latest/escape8259/index.html?search=u32+-%3E+bool Un-escapes a string following RFC8259 rules. ```APIDOC ## unescape ### Description Un-escape a string, following RFC8259 rules. ### Function Signature `unescape(s: &str) -> Result` ### Parameters - **s** (`&str`) - The string to unescape. ### Returns - **Result** - The unescaped string on success, or an error. ### Example ```rust use escape8259::unescape; let crab = r#"This is a crab: \ud83e\udd80"#; assert_eq!(unescape(crab).unwrap(), "This is a crab: πŸ¦€"); ``` ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/escape8259/all.html Escapes a string slice and writes the result into an existing String. ```APIDOC ## escape_str ### Description Escapes a string slice, writing the escaped output into a provided string. ### Method Function ### Signature pub fn escape_str(input: &str, output: &mut String) ### Parameters - **input** (&str) - Required - The string to escape. - **output** (&mut String) - Required - The buffer to write the escaped string into. ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/escape8259/index.html?search=std%3A%3Avec Escapes a &str following RFC8259 rules, returning a Cow. ```APIDOC ## escape_str ### Description Escapes a `&str` following RFC8259 rules, returning a `Cow`. ### Function Signature `pub fn escape_str(s: &str) -> Cow` ### Parameters - **s** (`&str`) - The input string to escape. ### Returns - **Cow** - The escaped string, either borrowed or owned. ### Example ```rust use escape8259::escape_str; let s = "hello\nworld"; let escaped = escape_str(s); assert_eq!(escaped, "hello\\nworld"); ``` ``` -------------------------------- ### escape_string Source: https://docs.rs/escape8259/latest/escape8259/index.html?search=std%3A%3Avec Escapes a String following RFC8259 rules, returning a new String. ```APIDOC ## escape_string ### Description Escapes a `String` following RFC8259 rules, returning a new `String`. ### Function Signature `pub fn escape_string(s: &str) -> String` ### Parameters - **s** (`&str`) - The input string to escape. ### Returns - **String** - The escaped string. ### Example ```rust use escape8259::escape_string; let s = String::from("A null (\0)"); assert_eq!(escape_string(&s), "A null (\\u0000)"); ``` ``` -------------------------------- ### pub fn unescape_str<'a>(s: &'a str) -> Result, UnescapeError> Source: https://docs.rs/escape8259/latest/escape8259/fn.unescape_str.html?search= Un-escapes a string following RFC8259 rules. Supports single-character escapes and UTF-16 escapes. May be faster than `unescape` when no unescaping is needed. ```APIDOC ## Function: unescape_str ### Description Un-escape a string, following RFC8259 rules. The only allowed single-character escapes are: `\" \\ \/ \b \f \n \r \t`. Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. Characters in the ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. This function may be faster than `unescape` if no un-escaping is needed, as it can return the input without performing any heap allocations. ### Signature ```rust pub fn unescape_str<'a>(s: &'a str) -> Result, UnescapeError> ``` ### Parameters - **s** (`&'a str`) - The input string to un-escape. ### Return Value - `Result, UnescapeError>` - On success, returns a `Cow` that either borrows the input (if no unescaping was needed) or owns an unescaped string. On failure, returns an `UnescapeError`. ### Errors - `UnescapeError` - Returned if the input contains invalid escape sequences or invalid UTF-16 escapes. ### Example ```rust use escape8259::unescape_str; let result = unescape_str("hello\\nworld").unwrap(); assert_eq!(result, "hello\nworld"); ``` ``` -------------------------------- ### unescape_string Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Un-escapes a string following RFC8259 rules, returning the input without allocation if no un-escaping is needed. ```APIDOC ## unescape_string ### Description Un-escapes a string following RFC8259 rules. This function may be faster than `unescape` if no un-escaping is needed, as it can return the input without performing any additional heap allocations. ### Method Function ### Signature `pub fn unescape_string(s: String) -> UnescapeResult` ### Parameters - **s** (String) - Required - The string to un-escape. ### Returns - **UnescapeResult** - The un-escaped string, or an error if the input contains invalid escapes. ### Behavior - The only allowed single-character escapes are: `\" \\ \/ /b /f /n /r /t`. - Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. - Characters in the ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. - If no backslash is present, the input is returned as-is without heap allocation. ``` -------------------------------- ### Full source code of escape8259 lib.rs Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search= The complete source code of the escape8259 crate's lib.rs file. It defines the UnescapeError type, the UnescapeState struct for collecting output characters, the parse_u16 helper, and the is_safe_char function. The code includes warnings for missing docs and unsafe code, and uses std::borrow::Cow, std::char::decode_utf16, and std::fmt::{Display, Write}. ```rust //! `escape8259` performs RFC8259-compliant string escaping and un-escaping. //! //! [RFC8259] is a JSON encoding standard. Many JSON encoders exist, but other //! RFCs use the same string escaping mechanism, so it's useful to be able to //! access the string escaping functions without needing a full JSON implementation. //! //! # Examples //! //! ``` //! use escape8259::{escape, unescape}; //! //! let s = "A null (\0) and a double-quote (\")"; //! assert_eq!(escape(s), r#"A null (\u0000) and a double-quote (\")"#); //! //! let crab = r#"This is a crab: \ud83e\udd80"#; //! assert_eq!(unescape(crab).unwrap(), "This is a crab: πŸ¦€"); //! //! // We accept encodings that weren't really necessary. //! assert_eq!(unescape(r#"\u0041\n"#).unwrap(), "A\n"); //! //! let multiline = r#"hello //! world"#; //! assert_eq!(escape(multiline), r#"hello\n world"#); //! ``` //! //! [RFC8259]: https://tools.ietf.org/html/rfc8259 #![warn(missing_docs)] #![forbid(unsafe_code)] #![warn(clippy::cast_possible_truncation)] use std::borrow::Cow; use std::char::decode_utf16; use std::fmt::{Display, Write}; /// An error occurred while unescaping. #[allow(clippy::empty_structs_with_brackets)] // FIXME: correct this if releasing a new major version. #[derive(Debug, Clone, Eq, PartialEq)] pub struct UnescapeError {} impl Display for UnescapeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("failed rfc8259 unescape") } } impl std::error::Error for UnescapeError {} type UnescapeResult = Result; // Used to collect output characters and queue u16 values for translation. struct UnescapeState { // The accumulated characters out: String, // Store a fragment of a large character for later decoding stash: u16, } impl UnescapeState { fn new() -> UnescapeState { UnescapeState { out: String::new(), stash: 0, } } fn from_str(init: &str) -> UnescapeState { UnescapeState { out: init.to_owned(), stash: 0, } } // Collect a new character fn push_char(&mut self, c: char) -> UnescapeResult<()> { if self.stash != 0 { return Err(UnescapeError {}); } self.out.push(c); Ok(()) } // Collect a new UTF16 word. This can either be one whole character, // or part of a larger character. fn push_u16(&mut self, x: u16) -> UnescapeResult<()> { let surrogate = (0xD800..=0xDFFF).contains(&x); match (self.stash, surrogate) { (0, false) => { // The std library only provides utf16 decode of an iterator, // so to decode a single character we wrap it in an array. // Hopefully the compiler will elide most of this extra work. let words = [x]; match decode_utf16(words.iter().copied()).next() { Some(Ok(c)) => { self.out.push(c); } _ => return Err(UnescapeError {}), } } (0, true) => self.stash = x, (_, false) => { return Err(UnescapeError {}); } (w, true) => { let words = [w, x]; match decode_utf16(words.iter().copied()).next() { Some(Ok(c)) => { self.out.push(c); self.stash = 0; } _ => return Err(UnescapeError {}), } } } Ok(()) } // If we queued up part of a UTF-16 encoded word but didn't // finish it, return an error. Otherwise, consume self and // return the accumulated String. fn finalize(self) -> UnescapeResult { if self.stash != 0 { return Err(UnescapeError {}); } Ok(self.out) } } fn parse_u16(s: &mut S) -> UnescapeResult where S: Iterator, { // Placeholder character in case the input doesn't have the 4 chars we want. let placeholders = std::iter::repeat('\0'); let hexnum: String = s.chain(placeholders).take(4).collect(); u16::from_str_radix(&hexnum, 16).map_err(|_| UnescapeError {}) } // RFC8259 says non-escaped characters must be in one of the following ranges: // %x20-21 / %x23-5B / %x5D-10FFFF fn is_safe_char(c: char) -> bool { ``` -------------------------------- ### escape Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html Escapes a string following RFC8259 rules. Accepts any type that implements AsRef. Always allocates a new String. ```APIDOC ## escape ### Description Escapes a string following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark `"`, reverse solidus `\` (backslash), and control characters (`0x00-1F`). If performance is important, and it's likely that the input string will not require any escaping, consider using `escape_str` or `escape_string` instead. ### Signature ```rust pub fn escape(s: S) -> String where S: AsRef, ``` ### Parameters - **s** (S) - Required - The input string, where `S: AsRef`. ### Returns - **String** - The escaped string. ### Example ```rust let escaped = escape("hello\nworld"); assert_eq!(escaped, "hello\\nworld"); ``` ``` -------------------------------- ### pub fn unescape(s: S) -> Result where S: AsRef Source: https://docs.rs/escape8259/latest/escape8259/fn.unescape.html?search=u32+-%3E+bool Un-escapes a string following RFC8259 rules. The only allowed single-character escapes are: \" \\ \/ \b \f \n \r \t. Any other character may be escaped in UTF-16 form: \uXXXX or \uXXXX\uXXXX. Characters in the ranges 0x20-21, 0x23-5B, 0x5D-10FFFF may appear un-escaped in the input. ```APIDOC ## Function: unescape ### Description Un-escapes a string following RFC8259 rules. The only allowed single-character escapes are: `\"` `\\` `\/` `\b` `\f` `\n` `\r` `\t`. Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. Characters in the ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. ### Signature ```rust pub fn unescape(s: S) -> Result where S: AsRef, ``` ### Parameters - `s` (S) - Required - The input string to un-escape. Must implement `AsRef`. ### Return Value - `Result` - The un-escaped string on success, or an `UnescapeError` on failure. ### Notes If performance is important, and it's likely that the input string will not require any un-escaping, consider using `unescape_str` or `unescape_string` instead. ``` -------------------------------- ### unescape_string Source: https://docs.rs/escape8259/latest/escape8259/all.html?search= Unescapes a string and returns the unescaped string. This is a convenience wrapper around the unescape function. ```APIDOC ## unescape_string ### Description Unescapes a string and returns the unescaped string. ### Function `unescape_string` ### Parameters - **input** (string) - Required - The string to unescape. ### Returns - **Result** - The unescaped string or an error. ``` -------------------------------- ### escape Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search= Escapes a string following RFC8259 rules. This is a generic convenience function that accepts any type implementing AsRef. Only characters that require escaping are escaped: quotation mark, backslash, and control characters (0x00-1F). ```APIDOC ## escape ### Description Escapes a string following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark, reverse solidus (backslash), and control characters (0x00-1F). If performance is important, and it's likely that the input string will not require any escaping, consider using `escape_str` or `escape_string` instead. ### Function Signature ```rust pub fn escape(s: S) -> String where S: AsRef, ``` ### Parameters - **s** (S) - Required - The input string, where S implements AsRef. ### Return Value - **String** - The escaped string. ### Example ```rust let escaped = escape("hello\nworld"); assert_eq!(escaped, "hello\\nworld"); ``` ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/escape8259/all.html?search= Escapes a string slice and writes the result to a formatter. This function is useful for building escaped strings incrementally. ```APIDOC ## escape_str ### Description Escapes a string slice and writes the result to a formatter. ### Function `escape_str` ### Parameters - **input** (string) - Required - The string slice to escape. - **formatter** (Formatter) - Required - The formatter to write the escaped string to. ### Returns - **Result** - The result of the formatting operation. ``` -------------------------------- ### Rust test: generic AsRef support Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Confirms that escape and unescape accept both &str and String arguments via the AsRef trait. ```rust #[test] fn test_generic_asref() { assert_eq!(escape("\n"), r#"\n"#); assert_eq!(escape(String::from("\n")), r#"\n"#); assert_eq!(escape(String::from("\n")), r#"\n"#); assert_eq!(unescape("abc"), Ok("abc".into())); assert_eq!(unescape(String::from("abc")), Ok("abc".into())); assert_eq!(unescape(String::from("abc")), Ok("abc".into())); } ``` -------------------------------- ### pub fn escape(s: S) -> String where S: AsRef Source: https://docs.rs/escape8259/latest/escape8259/fn.escape.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Escapes a string following RFC8259 rules. Only characters that require escaping are escaped: quotation mark, reverse solidus (backslash), and control characters (0x00-1F). For performance-sensitive cases where escaping is unlikely, consider using escape_str or escape_string instead. ```APIDOC ## Function: escape ### Description Escapes a string following RFC8259 rules. Only characters that require escaping are escaped: quotation mark `?`, reverse solidus `\` (backslash), and control characters (`0x00-1F`). ### Signature ```rust pub fn escape(s: S) -> String where S: AsRef, ``` ### Parameters - **s** (S) - Required - A string-like value that can be referenced as a `str`. The input string to escape. ### Return Value - **String** - The escaped string. ### Notes - If performance is important and it's likely the input string will not require escaping, consider using `escape_str` or `escape_string` instead. ``` -------------------------------- ### escape8259 Public API Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Documentation for the public functions `escape` and `unescape` provided by the `escape8259` crate. ```APIDOC ## escape8259::escape ### Description Escapes a string according to RFC8259, producing a new string with special characters escaped. This function is useful for encoding strings in JSON-compatible formats without requiring a full JSON implementation. ### Function Signature ```rust pub fn escape(input: &str) -> Cow<'_, str> ``` ### Parameters - **input** (`&str`) - The string to escape. ### Returns - **`Cow<'_, str>`** - An owned or borrowed string with all required characters escaped according to RFC8259. ### Example ```rust use escape8259::escape; let s = "A null (\0) and a double-quote (\")"; assert_eq!(escape(s), r#"A null (\u0000) and a double-quote (\")"#); ``` ``` ```APIDOC ## escape8259::unescape ### Description Unescapes a string that was escaped according to RFC8259, converting escape sequences back to their original characters. This function is useful for decoding JSON-compatible strings. ### Function Signature ```rust pub fn unescape(input: &str) -> Result ``` ### Parameters - **input** (`&str`) - The string to unescape. ### Returns - **`Result`** - On success, returns the unescaped string. On failure, returns an `UnescapeError`. ### Errors - Returns `UnescapeError` if the input contains invalid escape sequences or incomplete UTF-16 surrogate pairs. ### Example ```rust use escape8259::unescape; let crab = r#"This is a crab: \ud83e\udd80"#; assert_eq!(unescape(crab).unwrap(), "This is a crab: πŸ¦€"); ``` ``` -------------------------------- ### Rust test: UnescapeError implements Display and Error Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Ensures UnescapeError can be converted into a boxed std::error::Error, verifying it implements Display and Error traits. ```rust #[test] fn test_error_impl() { // This won't compile if UnescapeError doesn't impl Display + Error. let e = UnescapeError {}; let _x: Box = e.into(); } ``` -------------------------------- ### escape Source: https://docs.rs/escape8259/latest/escape8259/fn.escape.html?search= Escape a string following RFC8259 rules, escaping only required characters. ```APIDOC ## Function escape ### Description Escape a string, following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark `?`, reverse solidus `\` (backslash), and control characters (`0x00-1F`). ### Signature ```rust pub fn escape(s: S) -> String where S: AsRef, ``` ### Parameters - `s` (S) - Required - The input string to escape. Must implement `AsRef`. ### Return Value - `String` - The escaped string. ### Notes If performance is important’ and it is likely that the input will not require escaping, consider using `escape_str` or `escape_string` instead. ``` -------------------------------- ### escape_string Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html Escapes a String following RFC8259 rules. Returns the input unchanged if no escaping is needed, avoiding heap allocations. ```APIDOC ## escape_string ### Description Escapes a `String` following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark `"`, reverse solidus `\` (backslash), and control characters (`0x00-1F`). This function may be faster than `escape` if no escaping is needed, as it can return the input without performing any additional heap allocations. ### Signature ```rust pub fn escape_string(s: String) -> String ``` ### Parameters - **s** (String) - Required - The input string to escape. ### Returns - **String** - The escaped string. If no escaping is needed, the input is returned unchanged. ### Example ```rust let escaped = escape_string("hello\nworld".to_string()); assert_eq!(escaped, "hello\\nworld"); ``` ``` -------------------------------- ### unescape_str Source: https://docs.rs/escape8259/latest/escape8259/all.html Unescapes a string slice and writes the result into an existing String, returning a Result. ```APIDOC ## unescape_str ### Description Unescapes a string slice, writing the unescaped output into a provided string. Returns a Result indicating success or failure. ### Method Function ### Signature pub fn unescape_str(input: &str, output: &mut String) -> Result<(), UnescapeError> ### Parameters - **input** (&str) - Required - The string to unescape. - **output** (&mut String) - Required - The buffer to write the unescaped string into. ### Returns - **Result<(), UnescapeError>** - Ok(()) on success, or an `UnescapeError` on failure. ``` -------------------------------- ### unescape_str Source: https://docs.rs/escape8259/latest/escape8259/fn.unescape_str.html?search=u32+-%3E+bool Un-escape a string following RFC8259 rules. Supports single-character escapes and UTF-16 escapes. Returns a Cow that may borrow the input if no un-escaping is needed. ```APIDOC ## unescape_str ### Description Un-escape a string, following RFC8259 rules. The only allowed single-character escapes are: `\" \\ \/ \b \f \n \r \t`. Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. Characters in the ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. This function may be faster than `unescape` if no un-escaping is needed, as it can return the input without performing any heap allocations. ### Function Signature ```rust pub fn unescape_str<'a>(s: &'a str) -> Result, UnescapeError> ``` ### Parameters - **s** (`&'a str`) - The input string to un-escape. ### Return Value - `Result, UnescapeError>` - On success, returns a `Cow` that may borrow the input if no un-escaping is needed, or own a new string if un-escaping is performed. On failure, returns an `UnescapeError`. ``` -------------------------------- ### unescape_inner: Internal unescape implementation Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=std%3A%3Avec Internal helper that processes the string character by character, handling escape sequences. Supports single-character escapes (\", \\, \/, \b, \f, \n, \r, \t) and UTF-16 escapes (\uXXXX). Returns an error for invalid escapes or unsafe characters. ```rust fn unescape_inner(mut state: UnescapeState, s: &str) -> UnescapeResult { let mut ins = s.chars(); while let Some(c) = ins.next() { if c == '\\' { match ins.next() { None => { return Err(UnescapeError {}); } Some(d) => { match d { '"' | '\\' | '/' => state.push_char(d)?, 'b' => state.push_char('\x08')?, // backspace 'f' => state.push_char('\x0C')?, // formfeed 'n' => state.push_char('\n')?, // linefeed 'r' => state.push_char('\r')?, // carriage return 't' => state.push_char('\t')?, // tab 'u' => { let val = parse_u16(&mut ins)?; state.push_u16(val)?; } _ => { return Err(UnescapeError {}); } } } } } else if is_safe_char(c) { state.push_char(c)?; } else { return Err(UnescapeError {}); } } state.finalize() } ``` -------------------------------- ### escape Source: https://docs.rs/escape8259/latest/escape8259/all.html?search= Escapes a string according to RFC 8259. This function takes a string and returns an escaped version. ```APIDOC ## escape ### Description Escapes a string according to RFC 8259. ### Function `escape` ### Parameters - **input** (string) - Required - The string to escape. ### Returns - **String** - The escaped string. ``` -------------------------------- ### unescape_string Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Un-escapes a string following RFC8259 rules. Accepts a String and returns a String. This function may be faster than unescape if no un-escaping is needed, as it can return the input without performing any additional heap allocations. ```APIDOC ## unescape_string ### Description Un-escapes a string following RFC8259 rules. Accepts a String and returns a String. This function may be faster than unescape if no un-escaping is needed, as it can return the input without performing any additional heap allocations. ### Function Signature ```rust pub fn unescape_string(s: String) -> UnescapeResult ``` ### Parameters - **s** (String) - Required - The string to un-escape. ### Return Value - **UnescapeResult** - A `Result` containing the unescaped `String` on success, or an `UnescapeError` on failure. ### Behavior - The only allowed single-character escapes are: `\"`, `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`. - Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. - Characters in the ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. - If the input contains no backslashes, the function returns the input `String` without allocation. ### Example ```rust let input = String::from("hello\\nworld"); let result = unescape_string(input); assert_eq!(result.unwrap(), "hello\nworld"); ``` ``` -------------------------------- ### unescape_string Source: https://docs.rs/escape8259/latest/escape8259/fn.unescape_string.html?search= Un-escapes a string following RFC8259 rules. Supports single-character escapes (\", \\, \/, \b, \f, \n, \r, \t) and UTF-16 escapes (\uXXXX or \uXXXX\uXXXX). Characters in ranges 0x20-21, 0x23-5B, 0x5D-10FFFF may appear un-escaped. May be faster than unescape when no un-escaping is needed. ```APIDOC ## Function: unescape_string ### Description Un-escapes a string following RFC8259 rules. Supports single-character escapes (\", \\, \/, \b, \f, \n, \r, \t) and UTF-16 escapes (\uXXXX or \uXXXX\uXXXX). Characters in ranges 0x20-21, 0x23-5B, 0x5D-10FFFF may appear un-escaped. May be faster than unescape when no un-escaping is needed. ### Signature ```rust pub fn unescape_string(s: String) -> Result ``` ### Parameters - **s** (String) - Required - The input string to un-escape. ### Return Value - **Result** - On success, returns the un-escaped string. On failure, returns an UnescapeError. ### Behavior - Allowed single-character escapes: `\"`, `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`. - Any other character may be escaped in UTF-16 form: `\uXXXX` or `\uXXXX\uXXXX`. - Characters in ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped in the input. - This function may be faster than `unescape` if no un-escaping is needed, as it can return the input without performing any additional heap allocations. ``` -------------------------------- ### unescape Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search= Un-escapes a string following RFC8259 rules. Accepts any type that implements AsRef and returns an owned String. This is the general-purpose function for un-escaping. ```APIDOC ## unescape ### Description Un-escapes a string following RFC8259 rules. Accepts any type that implements AsRef and returns an owned String. This is the general-purpose function for un-escaping. ### Function Signature ```rust pub fn unescape(s: S) -> UnescapeResult where S: AsRef, ``` ### Parameters - **s** (S) - Required - The input string to un-escape. Must implement `AsRef`. ### Return Value - **UnescapeResult** - The un-escaped string, or an error if the input contains invalid escapes. ### Behavior - Supports single-character escapes: `\"`, `\\`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`. - Supports UTF-16 escapes: `\uXXXX` or `\uXXXX\uXXXX`. - Characters in ranges `0x20-21`, `0x23-5B`, `0x5D-10FFFF` may appear un-escaped. - Returns an error if an invalid escape sequence is encountered. ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Escapes a &str following RFC8259 rules. Returns a Cow that borrows the input if no escaping is needed, or owns a new escaped string otherwise. This function may be faster than escape if no escaping is needed, as it can return the input without performing any heap allocations. ```APIDOC ## escape_str ### Description Escapes a `&str` following RFC8259 rules. Only characters that require escaping will be escaped: quotation mark `"`, reverse solidus `\` (backslash), and the control characters (`0x00-1F`). This function may be faster than [`escape`] if no escaping is needed, as it can return the input without performing any heap allocations. ### Method Function ### Signature ```rust pub fn escape_str<'a>(s: &'a str) -> Cow<'a, str> ``` ### Parameters - **s** (&'a str) - Required - The input string to escape. ### Return Value - **Cow<'a, str>** - A borrowed `Cow` if no escaping is needed, otherwise an owned `Cow` with the escaped string. ### Example ```rust let borrowed = escape_str("safe"); assert!(matches!(borrowed, Cow::Borrowed(_))); let owned = escape_str("has \"quote\""); assert!(matches!(owned, Cow::Owned(_))); ``` ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/escape8259?search=std%3A%3Avec Escapes a &str following RFC8259 rules. This function is an alias for escape and returns an escaped String. ```APIDOC ## escape_str ### Description Escape a `&str`, following RFC8259 rules. ### Function Signature `pub fn escape_str(s: &str) -> String` ### Parameters - **s** (&str) - Required - The string to escape. ### Returns - **String** - The escaped string. ### Example ```rust use escape8259::escape_str; let escaped = escape_str("hello\nworld"); ``` ``` -------------------------------- ### unescape Source: https://docs.rs/escape8259/latest/escape8259/all.html?search= Unescapes a string according to RFC 8259. This function takes an escaped string and returns the unescaped version. ```APIDOC ## unescape ### Description Unescapes a string according to RFC 8259. ### Function `unescape` ### Parameters - **input** (string) - Required - The string to unescape. ### Returns - **Result** - The unescaped string or an error. ``` -------------------------------- ### escape_str Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html?search=u32+-%3E+bool Escapes a &str following RFC8259 rules. Only characters that require escaping are escaped: quotation mark, reverse solidus (backslash), and control characters (0x00-1F). This function may be faster than escape if no escaping is needed, as it can return the input without performing any heap allocations. ```APIDOC ## escape_str ### Description Escapes a `&str` following RFC8259 rules. Only characters that require escaping are escaped: quotation mark `?`, reverse solidus `\` (backslash), and the control characters (`0x00-1F`). This function may be faster than [`escape`] if no escaping is needed, as it can return the input without performing any heap allocations. ### Function Signature ```rust pub fn escape_str<'a>(s: &'a str) -> Cow<'a, str> ``` ### Parameters - **s** (&'a str) - Required - The input string slice to escape. ### Return Value - **Cow<'a, str>** - A borrowed `&str` if no escaping is needed, or an owned `String` if escaping is required. ### Example ```rust let escaped = escape_str("Hello \"World\""); ``` ``` -------------------------------- ### Rust test module for escape8259 functions Source: https://docs.rs/escape8259/latest/src/escape8259/lib.rs.html A Rust test module containing unit tests for the escape8259 library. It verifies round-trip escaping/unescaping, specific escape sequences, unescape error handling, generic AsRef support, and the Error trait implementation for UnescapeError. ```rust #[test] fn test_round_trip() { assert_round_trip("abc"); assert_round_trip("\n\r\t\x08\x0C\x00"); assert_round_trip(r#"\"#); assert_round_trip(r#"""#); assert_round_trip("Ξ£π„ž"); assert_round_trip(r#"\π„ž"#); assert_round_trip(r#"(β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻"#); } ``` ```rust #[test] fn test_escape() { assert_eq!(escape("\0"), r#"\u0000"#); assert_eq!(escape("\n"), r#"\n"#); assert_eq!(escape(r#"\"#), r#"\\"#); assert_eq!(escape(r#"""#), r#"\""#); assert_eq!(escape("Ξ£"), "Ξ£"); // U+03A3 assert_eq!(escape("π„ž"), "π„ž"); // U+1D11E } ``` ```rust #[test] fn test_unescape() { assert_eq!(unescape(r#"abc"#), Ok("abc".into())); assert_eq!(unescape(r#"ab\nc"#), Ok("ab\nc".into())); assert_eq!(unescape(r#"ab\zc"#), Err(UnescapeError {})); assert_eq!(unescape(r#" \"abc\" "#), Ok(" \"abc\" ".into())); assert_eq!(unescape(r#"π„ž"#), Ok("π„ž".into())); assert_eq!(unescape(r#"\π„ž"#), Err(UnescapeError {})); assert_eq!(unescape(r#"\uD834\uDD1E"#), Ok("π„ž".into())); assert_eq!(unescape(r#"\uD834"#), Err(UnescapeError {})); assert_eq!(unescape(r#"\uDD1E"#), Err(UnescapeError {})); assert_eq!(unescape("\t"), Err(UnescapeError {})); } ``` ```rust #[test] fn test_generic_asref() { assert_eq!(escape("\n"), r#"\n"#); assert_eq!(escape(String::from("\n")), r#"\n"#); assert_eq!(escape(String::from("\n")), r#"\n"#); assert_eq!(unescape("abc"), Ok("abc".into())); assert_eq!(unescape(String::from("abc")), Ok("abc".into())); assert_eq!(unescape(String::from("abc")), Ok("abc".into())); } ``` ```rust #[test] fn test_error_impl() { // This won't compile if UnescapeError doesn't impl Display + Error. let e = UnescapeError {}; let _x: Box = e.into(); } ```