Skip to content

Add new Literal::str_value, Literal::cstr_value and Literal::byte_str_value methods #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ default = ["proc-macro"]
# of a token.
span-locations = []

# This feature no longer means anything.
# Used for unstable `Literal` API.
nightly = []

[workspace]
Expand Down
30 changes: 30 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
clippy::vec_init_then_push
)]
#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
#![cfg_attr(feature = "nightly", feature(proc_macro_value))]

#[cfg(all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))]
compile_error! {"\
Expand Down Expand Up @@ -1273,6 +1274,35 @@ impl Literal {
pub unsafe fn from_str_unchecked(repr: &str) -> Self {
Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) })
}

/// Returns the unescaped string value if the current literal is a string or a string literal.
#[cfg(feature = "nightly")]
pub fn str_value(&self) -> Result<String, proc_macro::ConversionErrorKind> {
let imp::Literal::Compiler(ref compiler_lit) = self.inner else {
panic!("method only supported on compiler literals");
};
compiler_lit.str_value()
}

/// Returns the unescaped string value if the current literal is a c-string or a c-string
/// literal.
#[cfg(feature = "nightly")]
pub fn cstr_value(&self) -> Result<Vec<u8>, proc_macro::ConversionErrorKind> {
let imp::Literal::Compiler(ref compiler_lit) = self.inner else {
panic!("method only supported on compiler literals");
};
compiler_lit.cstr_value()
}

/// Returns the unescaped string value if the current literal is a byte string or a byte string
/// literal.
#[cfg(feature = "nightly")]
pub fn byte_str_value(&self) -> Result<Vec<u8>, proc_macro::ConversionErrorKind> {
let imp::Literal::Compiler(ref compiler_lit) = self.inner else {
panic!("method only supported on compiler literals");
};
compiler_lit.byte_str_value()
}
}

impl FromStr for Literal {
Expand Down