Skip to content
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

Implement string field accessors in Rust crate #2941

Merged
merged 2 commits into from
Jul 22, 2024

Conversation

FnControlOption
Copy link
Contributor

@FnControlOption FnControlOption commented Jul 17, 2024

For example, here's SymbolNode::unescaped:

pub fn unescaped(&self) -> &str {
    unsafe {
        let source = (*self.pointer).unescaped.source;
        let length = (*self.pointer).unescaped.length;
        let slice = std::slice::from_raw_parts(source, length);
        std::str::from_utf8_unchecked(slice)
    }
}

This assumes (possibly incorrectly) that string fields will always contain valid UTF-8. As an alternative, from_utf8_unchecked could be omitted by returning the plain &[u8] slice instead.

@@ -51,6 +51,7 @@ enum NodeFieldType {
#[serde(untagged)]
enum NodeFieldKind {
Concrete(String),
#[allow(dead_code)]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the necessary?

writeln!(file, " let source = (*self.pointer).{}.source;", field.name)?;
writeln!(file, " let length = (*self.pointer).{}.length;", field.name)?;
writeln!(file, " let slice = std::slice::from_raw_parts(source, length);")?;
writeln!(file, " std::str::from_utf8_unchecked(slice)")?;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah we can't do this. Strings can be contents of regexps, xstrings, strings, and symbols, all of which can have any of the 90 source encodings that Ruby supports. Better to return a u8 slice and have the consumer handle it.

@kddnewton kddnewton merged commit cb09d41 into ruby:main Jul 22, 2024
56 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants