-
Notifications
You must be signed in to change notification settings - Fork 7
lexer: encode \u escapes using locale encoding #51
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| // This file is part of the uutils awk package. | ||
| // | ||
| // For the full copyright and license information, please view the LICENSE | ||
| // files that was distributed with this source code. | ||
|
|
||
| //! Locale-aware encoding for `\u` escape sequences, matching gawk behavior. | ||
| //! | ||
| //! See: <https://www.gnu.org/software/gawk/manual/html_node/Escape-Sequences.html> | ||
|
|
||
| use encoding_rs::{EncoderResult, Encoding, UTF_8}; | ||
|
|
||
| /// Character encoding derived from the process locale (`LC_*` / `LANG`). | ||
| #[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| pub struct LocaleEncoding { | ||
| encoding: &'static Encoding, | ||
| /// `C` / `POSIX` locales only accept ASCII via `\u`. | ||
| ascii_only: bool, | ||
| } | ||
|
|
||
| impl LocaleEncoding { | ||
| pub fn utf8() -> Self { | ||
| Self { encoding: UTF_8, ascii_only: false } | ||
| } | ||
|
|
||
| /// `C` / `POSIX` locale: `\u` only encodes code points in ASCII. | ||
| pub fn ascii() -> Self { | ||
| Self { encoding: UTF_8, ascii_only: true } | ||
| } | ||
|
|
||
| /// ISO-8859-1 (Latin-1). | ||
| pub fn iso_8859_1() -> Self { | ||
| Self { | ||
| encoding: Encoding::for_label(b"iso-8859-1").unwrap_or(UTF_8), | ||
| ascii_only: false, | ||
| } | ||
| } | ||
|
|
||
| /// Detect encoding from `LC_ALL`, `LC_CTYPE`, or `LANG`. | ||
| pub fn detect() -> Self { | ||
| let name = std::env::var("LC_ALL") | ||
| .or_else(|_| std::env::var("LC_CTYPE")) | ||
| .or_else(|_| std::env::var("LANG")) | ||
| .unwrap_or_else(|_| "C.UTF-8".to_string()); | ||
| from_locale_name(&name) | ||
| } | ||
|
|
||
| /// Encode a Unicode scalar value for a `\u` escape in the current locale. | ||
| /// | ||
| /// Invalid code points and characters that cannot be represented in the | ||
| /// locale encoding become `?`, matching gawk. | ||
| pub fn encode_unicode_escape(self, codepoint: u32) -> Vec<u8> { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be more optimal if the user specifies the out-buffer as an argument, so we aren't allocating for each character just to then copy it into the arena. |
||
| if codepoint > 0x0010_FFFF || (0xD800..=0xDFFF).contains(&codepoint) { | ||
| return vec![b'?']; | ||
| } | ||
|
|
||
| let c = char::from_u32(codepoint).unwrap(); | ||
|
|
||
| if self.ascii_only && codepoint > 0x7F { | ||
| return vec![b'?']; | ||
| } | ||
|
Comment on lines
+52
to
+60
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can remove the let c = match char::try_from(codepoint) {
Ok(c) if !self.ascii_only || c.is_ascii() => c,
_ => return vec![b'?'],
}; |
||
|
|
||
| if self.encoding == UTF_8 && !self.ascii_only { | ||
| let mut buf = [0u8; 4]; | ||
| return c.encode_utf8(&mut buf).as_bytes().to_vec(); | ||
| } | ||
|
|
||
| let mut encoder = self.encoding.new_encoder(); | ||
| let mut buf = [0u8; 8]; | ||
| let ch = c.to_string(); | ||
| match encoder.encode_from_utf8_without_replacement(&ch, &mut buf, true) { | ||
| (EncoderResult::InputEmpty, _, written) if written > 0 => buf[..written].to_vec(), | ||
| _ => vec![b'?'], | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Default for LocaleEncoding { | ||
| fn default() -> Self { | ||
| Self::utf8() | ||
| } | ||
| } | ||
|
|
||
| fn from_locale_name(name: &str) -> LocaleEncoding { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this just be a method (constructor) of |
||
| let lower = name.to_ascii_lowercase(); | ||
| let extension = lower.rsplit_once('.').map(|(_, ext)| ext); | ||
| if lower == "c" || lower == "posix" || extension == Some("c") || extension == Some("posix") { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could be made more readable with something like this: let is_ascii = |c| matches!(c, "c" | "posix");
if is_ascii(&*lower) || extension.is_some_and(is_ascii) {
return LocaleEncoding::ascii();
} |
||
| return LocaleEncoding::ascii(); | ||
| } | ||
|
|
||
| let charset = name.rsplit('.').next().unwrap_or(name); | ||
| let label = charset.to_ascii_lowercase().replace('_', "-"); | ||
|
|
||
| if label.contains("utf-8") || label == "utf8" { | ||
| return LocaleEncoding::utf8(); | ||
| } | ||
|
|
||
| if let Some(encoding) = Encoding::for_label(label.as_bytes()) { | ||
| LocaleEncoding { encoding, ascii_only: false } | ||
| } else { | ||
| LocaleEncoding::utf8() | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be more optimal to fetch them all with
var_os(), and then combine it withstr's fallible UTF-8 check, so we can just pass astrof"C.UTF-8"otherwise.