[][src]Function quoted_string::quote_if_needed

pub fn quote_if_needed<'a, Spec, WQImpl>(
    input: &'a str,
    validator: &mut WQImpl
) -> Result<Cow<'a, str>, CoreError> where
    Spec: GeneralQSSpec,
    WQImpl: WithoutQuotingValidator

quotes the input string if needed

The validator decides if the value is valid without quoting it, the Spec type decides how quoting is done if needed. The Spec only specifies the format of quoting e.g. which values are allowed in a quoted-string but wether or not a string needs quoting can often depend on additional factor.

Note that this implementation expects the validator and spec to be in sync, i.e. what is valid without quoting does not need to be escaped when appearing in a quoted string.

Example

// use your own Spec
use quoted_string::test_utils::{TestSpec, TestUnquotedValidator};
use quoted_string::quote_if_needed;

let mut without_quoting = TestUnquotedValidator::new();
let quoted = quote_if_needed::<TestSpec, _>("simple", &mut without_quoting)
    .expect("only fails if input can not be represented as quoted string with used Spec");

// The used spec states a 6 character us-ascii word does not need to be represented as
// quoted string
assert_eq!(quoted, Cow::Borrowed("simple"));

let mut without_quoting = TestUnquotedValidator::new();
let quoted2 = quote_if_needed::<TestSpec, _>("more complex", &mut without_quoting).unwrap();
let expected: Cow<'static, str> = Cow::Owned("\"more complex\"".into());
assert_eq!(quoted2, expected);