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
2 changes: 2 additions & 0 deletions ext/json/ext/generator/generator.c
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,8 @@ static void generate_json_fallback(FBuffer *buffer, struct generate_json_data *d
VALUE tmp;
if (rb_respond_to(obj, i_to_json)) {
tmp = rb_funcall(obj, i_to_json, 1, vstate_get(data));
GET_STATE(data->vstate);
data->depth = state->depth;
Check_Type(tmp, T_STRING);
fbuffer_append_str(buffer, tmp);
} else {
Expand Down
4 changes: 2 additions & 2 deletions java/src/json/ext/Generator.java
Original file line number Diff line number Diff line change
Expand Up @@ -462,10 +462,10 @@ static void generateArray(ThreadContext context, Session session, RubyArray<IRub
generateFor(context, session, element, buffer);
}

int oldDepth = state.decreaseDepth();
state.depth = --depth;
if (!arrayNLEmpty) {
buffer.write(arrayNLBytes, arrayNLBegin, arrayNLSize);
Utils.repeatWrite(buffer, indentUnit, oldDepth);
Utils.repeatWrite(buffer, indentUnit, depth);
}

buffer.write((byte) ']');
Expand Down
2 changes: 1 addition & 1 deletion java/src/json/ext/GeneratorState.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public class GeneratorState extends RubyObject {
/**
* The current depth (inside a #to_json call)
*/
private int depth = 0;
protected int depth = 0;

static final ObjectAllocator ALLOCATOR = GeneratorState::new;

Expand Down
2 changes: 1 addition & 1 deletion lib/json/truffle_ruby/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,7 @@ def json_transform(state)
end
first = false
}
depth = state.depth -= 1
state.depth = depth -= 1
result << state.array_nl
result << state.indent * depth if indent
result << ']'
Expand Down
26 changes: 26 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,32 @@ def test_allow_nan
end
end

def test_depth_bad_to_json
obj = Object.new
def obj.to_json(state)
state.depth += 1
"{#{state.object_nl}"\
"#{state.indent * state.depth}\"foo\":#{state.space}1#{state.object_nl}"\
"#{state.indent * (state.depth - 1)}}"
end
assert_equal <<~JSON.chomp, JSON.pretty_generate([obj] * 2)
[
{
"foo": 1
},
{
"foo": 1
}
]
JSON
state = JSON::State.new(object_nl: "\n", array_nl: "\n", space: " ", indent: " ")
state.generate(obj)
assert_equal 1, state.depth # FIXME
state.depth = 0
state.generate([obj])
assert_equal 0, state.depth
end

def test_depth
pretty = { object_nl: "\n", array_nl: "\n", space: " ", indent: " " }
state = JSON.state.new(**pretty)
Expand Down