Skip to content

Fix handling of depth#911

Merged
byroot merged 1 commit into
ruby:masterfrom
etiennebarrie:fix-depth
Dec 3, 2025
Merged

Fix handling of depth#911
byroot merged 1 commit into
ruby:masterfrom
etiennebarrie:fix-depth

Conversation

@etiennebarrie

Copy link
Copy Markdown
Contributor

This adds a few tests around the handling of depth when an exception (in particular JSON::NestingError) is raised during JSON generation. The core idea is that state.depth shouldn't be changed when calling state.generate(obj) or obj.to_json(state). While we can't be sure in the last case for user-controlled classes, we can reasonably ensure that it works with Hash and Array.

For CRuby, the approach is to never use the current State object, and always start generation with a generate_json_data::vstate set to Qfalse. It's only the first time we need to call to_json, that we create a temporary State which can be freely mutated by user code, since we never copy depth back from State to generate_json_data. All subsequent calls to to_json will use the same State, setting its depth to the correct value at that point.

Since State is no longer mutated, we don't need State#generate_new anymore.

@byroot byroot merged commit ccca602 into ruby:master Dec 3, 2025
37 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.

2 participants