Skip to content

fix: serialize ByteBuffer remaining view - #7817

Open
DarrenChangJR wants to merge 1 commit into
alibaba:mainfrom
DarrenChangJR:fix/byte-buffer-view
Open

fix: serialize ByteBuffer remaining view#7817
DarrenChangJR wants to merge 1 commit into
alibaba:mainfrom
DarrenChangJR:fix/byte-buffer-view

Conversation

@DarrenChangJR

Copy link
Copy Markdown

What this PR does and why

Fastjson2 currently serializes heap-backed ByteBuffer values by returning the
entire backing array. This ignores the buffer's position, limit, and
arrayOffset, so a window exposing [1,2,3] from [9,1,2,3,8] is serialized
and parsed as all five bytes.

Direct and read-only buffers already serialize only their remaining view. This
change makes heap buffers follow the same rule:

  • retain the zero-copy fast path for a full backing-array view;
  • copy only arrayOffset + position .. arrayOffset + limit for heap windows
    and slices;
  • use a duplicate for buffers without an accessible array, avoiding temporary
    mutation and restoration of the source position.

Tests

The expanded ByteBufferTest covers:

  • heap buffers with nonzero position and a smaller limit;
  • heap slices with a nonzero backing-array offset;
  • equivalent direct and read-only views;
  • text JSON and JSONB round trips;
  • preservation of source position and limit;
  • existing full-array and Base64 behavior.

Validation performed:

  • focused ByteBufferTest;
  • mvn -pl core -DskipTests validate;
  • full mvn -pl core test suite: 7,982 tests, no failures or errors;
  • external Fastjson 1.2.83 / Fastjson2 compatibility matrix with equivalent
    heap, slice, and direct views.

Checklist

  • Heap, slice, direct, and read-only buffer implementations are covered.
  • Text JSON and JSONB paths are covered.
  • The common full-array path remains allocation-free.
  • No public API change is required.
中文说明

修改内容和原因

Fastjson2 当前对有底层数组的 ByteBuffer 直接返回完整 array(),忽略
positionlimitarrayOffset。因此,从 [9,1,2,3,8] 中仅暴露
[1,2,3] 的窗口,会被错误地序列化并反序列化为全部五个字节。

Direct 和只读 buffer 已经只序列化 remaining view。本修改统一该语义:完整底层
数组仍走零拷贝快速路径;heap window 和 slice 只复制有效区间;没有可访问数组的
buffer 通过 duplicate 读取,避免临时修改原对象的 position。

测试

测试覆盖非零 position/较小 limit 的 heap buffer、带非零 array offset 的
slice、等价的 direct 和只读 view、文本 JSON 与 JSONB 往返,以及源 position
和 limit 不变。定向测试、Maven validate 和完整 7,982 个 core 测试均通过。

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.

1 participant