Skip to content
Merged
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
12 changes: 6 additions & 6 deletions library/proc_macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ mod to_tokens;
use core::convert::From;
use core::ops::BitOr;
use std::borrow::Cow;
use std::ffi::CStr;
use std::ffi::{CStr, CString};
use std::ops::{Range, RangeBounds};
use std::path::PathBuf;
use std::str::FromStr;
Expand Down Expand Up @@ -1697,7 +1697,7 @@ impl Literal {
/// Returns the unescaped string value if the current literal is a c-string or a c-string
/// literal.
#[unstable(feature = "proc_macro_value", issue = "136652")]
pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
pub fn cstr_value(&self) -> Result<CString, ConversionErrorKind> {
self.0.symbol.with(|symbol| match self.0.kind {
bridge::LitKind::CStr => {
let mut error = None;
Expand All @@ -1718,16 +1718,16 @@ impl Literal {
Err(error)
} else {
buf.push(0);
Ok(buf)
// Safety: The `buf` content was already checked by the compiler when generating
// the literal.
unsafe { Ok(CString::from_vec_with_nul_unchecked(buf)) }
}
}
bridge::LitKind::CStrRaw(_) => {
// Raw strings have no escapes so we can convert the symbol
// directly to a `Lrc<u8>` after appending the terminating NUL
// char.
let mut buf = symbol.to_owned().into_bytes();
buf.push(0);
Ok(buf)
Ok(CString::new(symbol.to_owned()).expect("invalid cstr literal"))
}
_ => Err(ConversionErrorKind::InvalidLiteralKind),
})
Expand Down
11 changes: 11 additions & 0 deletions tests/ui/proc-macro/auxiliary/api/literal.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
// This code is part of a more global proc-macro testsuite. To run it:
// `./x.py test tests/ui/proc-macro/test.rs`. Also it's very frequent that even with modifications,
// it won't rerun, so don't forget to use `--force-rerun`.

// ignore-tidy-file-linelength

use std::ffi::CString;
use proc_macro::{EscapeError, Literal, ConversionErrorKind};

pub fn test() {
Expand Down Expand Up @@ -124,4 +129,10 @@ fn test_literal_value() {
Literal::byte_character(b'B').byte_character_value(),
Ok(b'B')
);

assert_eq!(Literal::string("aA").str_value(), Ok("aA".to_string()));
assert_eq!(Literal::string("\t").str_value(), Ok("\t".to_string()));

assert_eq!(Literal::c_string(c"aA").cstr_value().unwrap(), c"aA");
assert_eq!(Literal::c_string(c"\t").cstr_value().unwrap(), c"\t");
}
Loading