### Error::description Implementation for ParseUnicodeError (Deprecated) Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Deprecated method for getting a string description of the error. Prefer using the Display implementation or `to_string()`. ```rust fn description(&self) -> &str ``` -------------------------------- ### Error::cause Implementation for ParseUnicodeError (Deprecated) Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Deprecated method for getting the underlying cause of the error. Use `Error::source` instead, which supports downcasting. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Basic unescape usage Source: https://docs.rs/snailquote/latest/snailquote/fn.unescape.html Demonstrates the basic usage of the unescape function with a simple string. The result is unwrapped for direct printing. ```rust use snailquote::unescape; println!("{}", unescape("foo").unwrap()); // foo ``` -------------------------------- ### Parse OS Release PRETTY_NAME Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Demonstrates parsing the PRETTY_NAME field from simplified os-release files. It reads test data files and uses the unescape function to correctly interpret quoted and escaped values. ```rust let tests = vec![ ("fedora-19", "Fedora 19 (Schrödinger’s Cat)"), ("fedora-29", "Fedora 29 (Twenty Nine)"), ("gentoo", "Gentoo/Linux"), ("fictional", "Fictional $ OS: ` edition"), ]; for (file, pretty_name) in tests { let mut data = String::new(); std::fs::File::open(format!("./src/testdata/os-releases/{}", file)) .unwrap() .read_to_string(&mut data) .unwrap(); let mut found_prettyname = false; // partial os-release parser for line in data.lines() { if line.trim().starts_with("#") { continue; } let mut iter = line.splitn(2, "="); let key = iter.next().unwrap(); let value = iter.next().unwrap(); // assert we can parse the value let unescaped = unescape(value).unwrap(); if key == "PRETTY_NAME" { assert_eq!(unescaped, pretty_name); found_prettyname = true; } } assert!( found_prettyname, "expected os-release to have 'PRETTY_NAME' key" ); } ``` -------------------------------- ### Quickcheck for Shell Quoting Round Trip Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Tests shell quoting by escaping a string, passing it to `sh -c 'printf %s ...'`, and comparing the output to the original string. This requires the 'unsafe_tests' feature to be enabled. ```rust let s = s.replace(|c: char| c.is_ascii_control() || !c.is_ascii(), ""); let escaped = escape(&s); println!("escaped '{}' as '{}'", s, escaped); let output = Command::new("sh").args(vec!["-c", &format!("printf '%s' {}", escaped)]).output().unwrap(); if !output.status.success() { panic!("printf %s {} did not exit with success", escaped); } let echo_output = String::from_utf8(output.stdout).unwrap(); println!("printf gave it back as '{}'", echo_output); echo_output == s ``` -------------------------------- ### Escape strings with snailquote::escape Source: https://docs.rs/snailquote/latest/snailquote/fn.escape.html Demonstrates various scenarios for escaping strings using `snailquote::escape`. This includes strings that require no escaping, strings that can be single-quoted, and strings that necessitate double quotes with internal escapes. ```rust use snailquote::escape; println!("{}", escape("foo")); // no escapes needed // foo println!("{}", escape("String with spaces")); // single-quoteable // 'String with spaces' println!("{}", escape("東方")); // no escapes needed // 東方 println!("{}", escape("\"new\nline\"")); // escape needed // "\"new\nline\"" ``` -------------------------------- ### Quickcheck for Round Trip Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Uses the QuickCheck library to property-test the round-trip capability of the escape and unescape functions with arbitrary strings. ```rust s == unescape(&escape(&s)).unwrap() ``` -------------------------------- ### Error::provide Implementation for ParseUnicodeError (Nightly) Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html A nightly-only experimental API for providing type-based access to error context, intended for error reporting. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### escape Source: https://docs.rs/snailquote/latest/snailquote/all.html Escapes a string according to snailquote rules. ```APIDOC ## escape ### Description Escapes a given string. ### Function Signature `fn escape(s: &str) -> String` ### Parameters * **s** (*&str*) - The string slice to escape. ### Returns * (*String*) - The escaped string. ``` -------------------------------- ### escape Source: https://docs.rs/snailquote Escapes the provided string with shell-like quoting and escapes. Strings that do not need to be escaped will be returned unchanged. ```APIDOC ## escape ### Description Escape the provided string with shell-like quoting and escapes. Strings which do not need to be escaped will be returned unchanged. ### Function Signature `fn escape(s: &str) -> String` ``` -------------------------------- ### unescape Source: https://docs.rs/snailquote/latest/index.html Parses a provided shell-like quoted string, such as one produced by `escape`. ```APIDOC ## unescape ### Description Parse the provided shell-like quoted string, such as one produced by escape. ### Function Signature ```rust fn unescape>(s: S) -> Result ``` ### Parameters * `s` - The shell-like quoted string to parse. ### Returns A `Result` which is `Ok(String)` containing the unescaped string on success, or `Err(UnescapeError)` if parsing fails. ``` -------------------------------- ### unescape Source: https://docs.rs/snailquote/latest/snailquote/all.html Unescapes a string that has been escaped by snailquote. ```APIDOC ## unescape ### Description Unescapes a given string. ### Function Signature `fn unescape(s: &str) -> Result` ### Parameters * **s** (*&str*) - The string slice to unescape. ### Returns * (*Result*) - A Result containing the unescaped string or an `UnescapeError` if the unescaping fails. ``` -------------------------------- ### escape Source: https://docs.rs/snailquote/latest/index.html Escapes a provided string with shell-like quoting and escapes. Strings that do not require escaping are returned unchanged. ```APIDOC ## escape ### Description Escape the provided string with shell-like quoting and escapes. Strings which do not need to be escaped will be returned unchanged. ### Function Signature ```rust fn escape>(s: S) -> String ``` ### Parameters * `s` - The string to escape. ### Returns A `String` containing the escaped version of the input string. ``` -------------------------------- ### escape Source: https://docs.rs/snailquote/latest/snailquote/index.html Escapes a provided string using shell-like quoting and escape characters. If the string does not require escaping, it is returned unchanged. ```APIDOC ## escape ### Description Escape the provided string with shell-like quoting and escapes. Strings which do not need to be escaped will be returned unchanged. ### Function Signature ```rust fn escape(s: &str) -> String ``` ### Parameters * **s** (*&str*) - The string slice to be escaped. ### Returns * (*String*) - The escaped string. ``` -------------------------------- ### Unescape single-quoted string Source: https://docs.rs/snailquote/latest/snailquote/fn.unescape.html Shows how to unescape a string enclosed in single quotes, preserving spaces within the quotes. The result is unwrapped for printing. ```rust use snailquote::unescape; println!("{}", unescape("'String with spaces'").unwrap()); // String with spaces ``` -------------------------------- ### Error Trait Implementation Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Demonstrates the implementation of the standard `Error` trait for `ParseUnicodeError`, allowing for error chaining and introspection. ```APIDOC ### impl Error for ParseUnicodeError #### fn source(&self) -> Option<&(dyn Error + 'static)> Returns the lower-level source of this error, if any. #### fn description(&self) -> &str Deprecated since 1.42.0: use the Display impl or to_string(). #### fn cause(&self) -> Option<&dyn Error> Deprecated since 1.33.0: replaced by Error::source, which can support downcasting ``` -------------------------------- ### PartialEq::eq Implementation for ParseUnicodeError Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Tests if two ParseUnicodeError instances are equal. Used by the `==` operator. ```rust fn eq(&self, other: &ParseUnicodeError) -> bool ``` -------------------------------- ### Error::source Implementation for ParseUnicodeError Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Provides the lower-level source error if available. This is useful for error chaining and debugging. ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` -------------------------------- ### unescape Source: https://docs.rs/snailquote/latest/snailquote/fn.unescape.html Parses the provided shell-like quoted string, such as one produced by escape. It can handle single quotes, double quotes with a set of escapes similar to ANSI-C, and Unicode escapes of the form \"\u{01ff}\". Multiple different quoting styles may be used in one string. ```APIDOC ## unescape ### Description Parses the provided shell-like quoted string, such as one produced by escape. It can handle single quotes, double quotes with a set of escapes similar to ANSI-C, and Unicode escapes of the form \"\u{01ff}\". Multiple different quoting styles may be used in one string. ### Function Signature ```rust pub fn unescape(s: &str) -> Result ``` ### Details Unescape is able to handle single quotes (which cannot contain any additional escapes), double quotes (which may contain a set of escapes similar to ANSI-C, i.e. ‘\n’, ‘\r’, ‘'’, etc. Unescape will also parse unicode escapes of the form “\u{01ff}”. See char::escape_unicode in the Rust standard library for more information on these escapes. Multiple different quoting styles may be used in one string, for example, the following string is valid: `'some spaces'_some_unquoted_"and a \t tab"`. The full set of supported escapes between double quotes may be found below: Escape| Unicode| Description ---|---|--- \a| \u{07}| Bell \b| \u{08}| Backspace \v| \u{0B}| Vertical tab \f| \u{0C}| Form feed \n| \u{0A}| Newline \r| \u{0D}| Carriage return \t| \u{09}| Tab \e| \u{1B}| Escape \E| \u{1B}| Escape \\| \u{5C}| Backslash '| \u{27}| Single quote "| \u{22}| Double quote $| \u{24}| Dollar sign (sh compatibility) `| \u{60}| Backtick (sh compatibility) \u{XX}| \u{XX}| Unicode character with hex code XX ### Errors The returned result can display a human readable error if the string cannot be parsed as a valid quoted string. ### Examples ```rust use snailquote::unescape; println!("{}", unescape("foo").unwrap()); // foo println!("{}", unescape("'String with spaces'").unwrap()); // String with spaces println!("{}", unescape("\"new\\\\nline\"").unwrap()); // new // line println!("{}", unescape("'some spaces'_some_unquoted_\"and a \\t tab\"").unwrap()); // some spaces_some_unquoted_and a tab ``` ``` -------------------------------- ### escape Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Escapes a provided string with shell-like quoting and escapes. Strings that do not need escaping are returned unchanged. It prefers single quotes when possible, otherwise uses double quotes and escapes necessary characters. ```APIDOC ## escape ### Description Escapes a provided string with shell-like quoting and escapes. Strings that do not need escaping are returned unchanged. It prefers single quotes when possible, otherwise uses double quotes and escapes necessary characters. ### Function Signature `pub fn escape(s: &str) -> Cow` ### Parameters * `s` (*str*) - The string slice to be escaped. ### Returns * `Cow` - The escaped string. Returns the original string if no escaping is needed, otherwise a new `Cow` containing the escaped version. ### Examples ```rust use snailquote::escape; // No escapes needed assert_eq!(escape("foo"), "foo"); // Single-quoteable string assert_eq!(escape("String with spaces"), "'String with spaces'"); // String with special characters needing double quotes and escapes assert_eq!(escape("\"new\nline\""), "\"\\\"new\\nline\\\"\""); ``` ``` -------------------------------- ### PartialEq::ne Implementation for ParseUnicodeError Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Tests if two ParseUnicodeError instances are not equal. Used by the `!=` operator. ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### unescape Source: https://docs.rs/snailquote/latest/snailquote/index.html Parses a shell-like quoted string, such as one produced by the `escape` function, back into its original form. ```APIDOC ## unescape ### Description Parse the provided shell-like quoted string, such as one produced by escape. ### Function Signature ```rust fn unescape(s: &str) -> Result ``` ### Parameters * **s** (*&str*) - The shell-like quoted string to be parsed. ### Returns * (*Result*) - A `Result` containing the unescaped string on success, or an `UnescapeError` on failure. ``` -------------------------------- ### Test Unescape Errors Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Tests various error conditions for the unescape function, including invalid escape sequences and unicode parsing failures. It also demonstrates how to format and compare unescape errors. ```rust assert_eq!( unescape("\"\\x\""), Err(UnescapeError::InvalidEscape { escape: "\\x".to_string(), index: 2, string: "\"\\x\"".to_string() }) ); assert_eq!( unescape("\"\\u6771}\""), Err(UnescapeError::InvalidUnicode { source: ParseUnicodeError::BraceNotFound, index: 2, string: "\"\\u6771}\"".to_string() }) ); // Can't compare ParseIntError directly until 'int_error_matching' becomes stable assert_eq!( format!("{}", unescape("\"\\u{{qqqq}}\"").err().unwrap()), "\\u could not be parsed at 2 in \"\\u{{qqqq}}\": could not parse qqqq as u32 hex: invalid digit found in string" ); assert_eq!( unescape("\"\\u{{ffffffff}}\""), Err(UnescapeError::InvalidUnicode { source: ParseUnicodeError::ParseUnicodeFailed { value: 0xffffffff }, index: 2, string: "\"\\u{{ffffffff}}\"".to_string() }) ); ``` -------------------------------- ### Unescape mixed quoting styles with tab escape Source: https://docs.rs/snailquote/latest/snailquote/fn.unescape.html Demonstrates unescaping a string that combines single quotes, unquoted parts, and double quotes with a tab escape sequence (`\t`). The result is unwrapped for printing. ```rust use snailquote::unescape; println!("{}", unescape("'some spaces'_some_unquoted_\"and a \\t tab\"").unwrap()); // some spaces_some_unquoted_and a tab ``` -------------------------------- ### escape Source: https://docs.rs/snailquote/latest/snailquote/fn.escape.html Escapes a string with shell-like quoting and escapes. Strings that do not require escaping are returned unchanged. The function prefers to avoid quoting, then uses single quotes, and finally double quotes if necessary. ```APIDOC ## Function escape ```rust pub fn escape(s: &str) -> Cow<'_, str> ``` ### Description Escape the provided string with shell-like quoting and escapes. Strings which do not need to be escaped will be returned unchanged. Escape will prefer to avoid quoting when possible. When quotes are required, it will prefer single quotes (which have simpler semantics, namely no escaping). In all other cases it will use double quotes and escape whatever characters it needs to. For the full list of escapes which will be used, see the table in unescape. ### Examples ```rust use snailquote::escape; println!("{}", escape("foo")); // no escapes needed // foo println!("{}", escape("String with spaces")); // single-quoteable // 'String with spaces' println!("{}", escape("東方")); // no escapes needed // 東方 println!("{}", escape("\"new\nline\"")); // escape needed // "\"new\nline\"" ``` ``` -------------------------------- ### TryInto::try_into Implementation for T Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html A generic implementation for attempting to convert a value of type `T` into type `U`. The `Error` type is determined by the `TryFrom` implementation for `U`. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Test Round Trip Escaping and Unescaping Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Verifies that the escape and unescape functions correctly handle a variety of string inputs, ensuring data integrity through round-trip conversions. Includes common characters, control characters, and special sequences. ```rust let test_cases = vec![ "東方", "foo bar baz", "\\", "\0", "\"'", "\"'''''\"()())}{{}{}{{{!////", "foo;bar", ]; for case in test_cases { assert_eq!(unescape(&escape(case)), Ok(case.to_owned())); } ``` -------------------------------- ### Unescape String Literal Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Handles the unescaping of string literals, including standard escape sequences and Unicode characters. It correctly parses various escape codes like \n, \t, \u{...}, and others within quoted strings. ```rust fn unescape(s: &str) -> Result { let mut res = String::with_capacity(s.len()); let mut chars = s.chars().enumerate().peekable(); let mut in_single_quote = false; let mut in_double_quote = false; while let Some((idx, c)) = chars.next() { if in_single_quote { if c == '\\'' { if let Some((_, c2)) = chars.next() { match c2 { '\'' => { res.push('a'); continue; } _ => { return Err(UnescapeError::InvalidEscape { escape: format!("{}", c2), index: idx, string: String::from(s), }); } } } else { return Err(UnescapeError::InvalidEscape { escape: String::from(c), index: idx, string: String::from(s), }); } } else if c == '\'' { in_single_quote = false; continue; } else { res.push(c); } continue; } if in_double_quote { if c == '\\'' { match chars.peek() { Some((_, c2)) => { res.push(match c2 { 'a' => '\u{07}', 'b' => '\u{08}', 'v' => '\u{0B}', 'f' => '\u{0C}', 'n' => '\n', 'r' => '\r', 't' => '\t', 'e' | 'E' => '\u{1B}', '\\' => '\\', '\'' => '\'', '"' => '"', '$' => '$', '`' => '`', ' ' => ' ', 'u' => parse_unicode(&mut chars).map_err(|x| { UnescapeError::InvalidUnicode { source: x, index: idx, string: String::from(s), } })?, _ => { return Err(UnescapeError::InvalidEscape { escape: format!("{}{}", c, c2), index: idx, string: String::from(s), }); } }); chars.next(); // Consume the second character continue; } _ => { return Err(UnescapeError::InvalidEscape { escape: String::from(c), index: idx, string: String::from(s), }); } } } else if c == '"' { in_double_quote = false; continue; } else { res.push(c); } continue; } if c == '\\'' { match chars.peek() { Some((_, c2)) => { res.push(match c2 { 'a' => '\u{07}', 'b' => '\u{08}', 'v' => '\u{0B}', 'f' => '\u{0C}', 'n' => '\n', 'r' => '\r', 't' => '\t', 'e' | 'E' => '\u{1B}', '\\' => '\\', '\'' => '\'', '"' => '"', '$' => '$', '`' => '`', ' ' => ' ', 'u' => parse_unicode(&mut chars).map_err(|x| { UnescapeError::InvalidUnicode { source: x, index: idx, string: String::from(s), } })?, _ => { return Err(UnescapeError::InvalidEscape { escape: format!("{}{}", c, c2), index: idx, string: String::from(s), }); } }); chars.next(); // Consume the second character continue; } _ => { return Err(UnescapeError::InvalidEscape { escape: format!("{}", c), index: idx, string: String::from(s), }); } } } else if c == '\'' { in_single_quote = true; continue; } else if c == '"' { in_double_quote = true; continue; } res.push(c); } Ok(res) } ``` -------------------------------- ### TryFrom::try_from Implementation for T Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html A generic implementation for attempting to convert a value of type `U` into type `T`. The `Error` type is `Infallible` if the conversion is always possible. ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Parse Unicode Escape Sequence Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Parses a Unicode escape sequence of the form \u{...}. This helper function expects the iterator to be positioned after 'u' and before '{'. It collects hexadecimal characters until '}' and converts them to a char. ```rust fn parse_unicode(chars: &mut I) -> Result where I: Iterator, { match chars.next() { Some((_, '{')) => {} _ => { return Err(ParseUnicodeError::BraceNotFound); } } let unicode_seq: String = chars .take_while(|&(_, c)| c != '}') .map(|(_, c)| c) .collect(); u32::from_str_radix(&unicode_seq, 16) .map_err(|e| ParseUnicodeError::ParseHexFailed { source: e, string: unicode_seq, }) .and_then(|u| { char::from_u32(u).ok_or_else(|| ParseUnicodeError::ParseUnicodeFailed { value: u }) }) } ``` -------------------------------- ### UnescapeError Enum Definition Source: https://docs.rs/snailquote/latest/snailquote/enum.UnescapeError.html Defines the possible errors that can occur during string unescaping. ```APIDOC ## Enum UnescapeError Error type of unescape. ### Variants #### InvalidEscape This variant indicates an invalid escape sequence was found. ##### Fields - `escape`: String - The invalid escape sequence encountered. - `index`: usize - The starting index of the invalid escape sequence in the original string. - `string`: String - The original string being unescaped. #### InvalidUnicode This variant indicates an invalid Unicode escape sequence was found. ##### Fields - `source`: ParseUnicodeError - The underlying error from parsing the Unicode escape sequence. - `index`: usize - The starting index of the invalid Unicode escape sequence in the original string. - `string`: String - The original string being unescaped. ``` -------------------------------- ### Escape Special Unicode Characters Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Converts a given unicode character into an escape sequence. Prefers human-readable escapes like '\n' over '\u{0a}', but falls back to unicode escaping. This is an internal helper function. ```rust // escape_character is an internal helper method which converts the given unicode character into an // escape sequence. It is assumed the character passed in *must* be escaped (e.g. it is some non-printable // or unusual character). // escape_character will prefer more human readable escapes (e.g. '\n' over '\u{0a}'), but will // fall back on dumb unicode escaping. // It is similar to rust's "char::escape_default", but supports additional escapes that rust does // not. For strings that don't contain these unusual characters, it's identical to 'escape_default'. fn escape_character(c: char) -> String { match c { '\u{07}' => "\\a".to_string(), '\u{08}' => "\\b".to_string(), '\u{0b}' => "\\v".to_string(), ``` -------------------------------- ### Escape String with Shell-like Quoting Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Escapes a string for shell-like quoting. It avoids quoting when possible, prefers single quotes for simple cases, and uses double quotes with necessary escapes for complex strings. Handles various special characters and whitespace. ```rust extern crate quickcheck; extern crate quickcheck_macros; extern crate unicode_categories; use std::borrow::Cow; use std::num::ParseIntError; use std::{char, str}; use thiserror::Error; use unicode_categories::UnicodeCategories; /// Escape the provided string with shell-like quoting and escapes. /// Strings which do not need to be escaped will be returned unchanged. /// /// # Details /// /// Escape will prefer to avoid quoting when possible. When quotes are required, it will prefer /// single quotes (which have simpler semantics, namely no escaping). In all other cases it will /// use double quotes and escape whatever characters it needs to. /// /// For the full list of escapes which will be used, see the table in /// [unescape](unescape). /// /// # Examples /// ``` /// use snailquote::escape; /// # // The println/assert duplication is because I want to show the output you'd get without /// # // rust's string quoting/escaping getting in the way /// # // Ideally we could just assert on stdout, not duplicate, see /// # // https://github.com/rust-lang/rfcs/issues/2270 /// println!("{}", escape("foo")); // no escapes needed /// // foo /// # assert_eq!(escape("foo"), "foo"); /// println!("{}", escape("String with spaces")); // single-quoteable /// // 'String with spaces' /// # assert_eq!(escape("String with spaces"), "'String with spaces'"); /// println!("{}", escape("東方")); // no escapes needed /// // 東方 /// # assert_eq!(escape("東方"), "東方"); /// println!("{}", escape("\"new\nline\"")); // escape needed /// // \"new\nline\"" /// # assert_eq!(escape("\"new\nline\""), "\"\\\"new\\nline\\\"\""); /// ``` // escape performs some minimal 'shell-like' escaping on a given string pub fn escape(s: &str) -> Cow { let mut needs_quoting = false; let mut single_quotable = true; for c in s.chars() { let quote = match c { // Special cases, can't be single quoted '\'' | '\\' => { single_quotable = false; true }, // ' ' is up here before c.is_whitespace() because it's the only whitespace we can // single quote safely. Things like '\t' need to be escaped. '"' | ' ' => true, // Special characters in shells that can error out or expand if not quoted '(' | ')' | '&' | '~' | '$' | '#' | '`' | ';' => true, // sh globbing chars '*' | '?' | '!' | '[' => true, // redirects / pipes '>' | '<' | '|' => true, c if c.is_whitespace() || c.is_separator() || c.is_other() => { // we need to escape most whitespace (i.e. \t), so we need double quotes. single_quotable = false; true }, _ => false, }; if quote { needs_quoting = true; } if needs_quoting && !single_quotable { // We know we'll need double quotes, no need to check further break; } } if !needs_quoting { return Cow::from(s); } if single_quotable { return format!("'{}'", s).into(); } // otherwise we need to double quote it let mut output = String::with_capacity(s.len()); output.push('"'); for c in s.chars() { if c == '"' { output += "\\\""; } else if c == '\\' { output += "\\\\"; } else if c == ' ' { // avoid 'escape_unicode' for ' ' even though it's a separator output.push(c); } else if c == '$' { output += "\\$"; } else if c == '`' { output += "\\`"; } else if c.is_other() || c.is_separator() { output += &escape_character(c); } else { output.push(c); } } output.push('"'); output.into() } ``` -------------------------------- ### Unescape Shell-like Quoted Strings Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Parses shell-like quoted strings, handling single and double quotes, and various escape sequences including Unicode. Use this function to convert escaped strings back into their original form. ```rust use snailquote::unescape; # // The println/assert duplication is because I want to show the output you'd get without # // rust's string quoting/escaping getting in the way # // Ideally we could just assert on stdout, not duplicate, see # // https://github.com/rust-lang/rfcs/issues/2270 println!("{}", unescape("foo").unwrap()); // foo # assert_eq!(unescape("foo").unwrap(), "foo"); println!("{}", unescape("'String with spaces'").unwrap()); // String with spaces # assert_eq!(unescape("'String with spaces'").unwrap(), "String with spaces"); println!("{}", unescape("\"new\\nline\"").unwrap()); // new // line # assert_eq!(unescape("\"new\\nline\"").unwrap(), "new\nline"); println!("{}", unescape("'some spaces'_some_unquoted_\"and a \\t tab\""").unwrap()); // some spaces_some_unquoted_and a tab # assert_eq!(unescape("'some spaces'_some_unquoted_\"and a \\t tab\""").unwrap(), "some spaces_some_unquoted_and a tab"); ``` -------------------------------- ### Escape String Literal Source: https://docs.rs/snailquote/latest/src/snailquote/lib.rs.html Escapes a given string by converting special characters into their respective escape sequences. This is useful for creating string literals that can be safely represented or transmitted. ```rust fn escape(s: &str) -> String { let mut res = String::with_capacity(s.len() + 2); res.push('"'); for c in s.chars() { match c { '\'' => res.push_str("\'\'"), '"' => res.push_str("\"\""), '\\' => res.push_str("\\\\"), '\n' => res.push_str("\\n"), '\r' => res.push_str("\\r"), '\t' => res.push_str("\\t"), '\u{07}' => res.push_str("\\a"), '\u{08}' => res.push_str("\\b"), '\u{0B}' => res.push_str("\\v"), '\u{0C}' => res.push_str("\\f"), '\u{1B}' => res.push_str("\\e"), '$' => res.push_str("\\$"), '`' => res.push_str("\\`"), c => { if c.is_control() { res.push_str(&format!("\\u{{{:x}}}", c as u32)); } else { res.push(c); } } } } res.push('"'); res } ``` -------------------------------- ### Unescape double-quoted string with newline escape Source: https://docs.rs/snailquote/latest/snailquote/fn.unescape.html Illustrates unescaping a double-quoted string containing a newline escape sequence (`\n`). The result is unwrapped for printing. ```rust use snailquote::unescape; println!("{}", unescape("\"new\\nline\"").unwrap()); // new // line ``` -------------------------------- ### ParseUnicodeError Enum Definition Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html Defines the possible errors during Unicode parsing. Use this enum to handle specific parsing failures. ```rust pub enum ParseUnicodeError { BraceNotFound, ParseHexFailed { source: ParseIntError, string: String, }, ParseUnicodeFailed { value: u32, }, } ``` -------------------------------- ### UnescapeError Enum Definition Source: https://docs.rs/snailquote/latest/snailquote/enum.UnescapeError.html Defines the UnescapeError enum with its variants: InvalidEscape and InvalidUnicode. Use this enum to handle potential errors during string unescaping. ```rust pub enum UnescapeError { InvalidEscape { escape: String, index: usize, string: String, }, InvalidUnicode { source: ParseUnicodeError, index: usize, string: String, }, } ``` -------------------------------- ### ParseUnicodeError Enum Definition Source: https://docs.rs/snailquote/latest/snailquote/enum.ParseUnicodeError.html The ParseUnicodeError enum defines the possible errors encountered when parsing Unicode characters, such as missing braces, failed hexadecimal parsing, or general Unicode parsing failures. ```APIDOC ## Enum ParseUnicodeError Source error type of UnescapeError::InvalidUnicode. ### Variants * **BraceNotFound**: Indicates that a required brace was not found during parsing. * **ParseHexFailed** { `source`: ParseIntError, `string`: String }: Indicates a failure to parse a hexadecimal string. It includes the original `ParseIntError` and the problematic `string`. * **ParseUnicodeFailed** { `value`: u32 }: Indicates a general failure to parse a Unicode character, providing the problematic `value`. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.