wenshao commented on code in PR #3901:
URL: https://github.com/apache/fory/pull/3901#discussion_r3696496166


##########
go/fory/row/infer.go:
##########
@@ -0,0 +1,252 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package row
+
+import (
+       "fmt"
+       "reflect"
+       "sort"
+       "strings"
+       "time"
+       "unicode"
+       "unicode/utf8"
+
+       fory "github.com/apache/fory/go/fory"
+)
+
+var (
+       goDateType     = reflect.TypeOf(fory.Date{})
+       goTimeType     = reflect.TypeOf(time.Time{})
+       goDurationType = reflect.TypeOf(time.Duration(0))
+)
+
+// InferSchema infers the row schema for a struct type or pointer to
+// struct, including every exported field not tagged `fory:"ignore"`.
+//
+// Fields are sorted by their lowerCamel name and named by its
+// snake_case form (UserName -> user_name), matching Java's schema
+// inference so both languages derive identical schemas.
+//
+// Type mapping:
+//   - bool, int8/16/32/64, float32/64: same-width row types; int maps to int64
+//   - string, []byte: string and binary, nullable
+//   - slices, maps, nested structs: list, map, and struct, nullable
+//   - *T: the row type of T, nullable
+//   - fory.Date, time.Time, time.Duration: date32, timestamp, duration
+//
+// Unsigned integers, fixed-size arrays, nested pointers, and pointer
+// map keys are unsupported and return an error.
+func InferSchema(t reflect.Type) (*Schema, error) {
+       layout, err := inferStructLayout(t, nil)
+       if err != nil {
+               return nil, err
+       }
+       return layout.schema, nil
+}
+
+// structLayout maps schema ordinals back to Go struct field indexes.
+type structLayout struct {
+       schema  *Schema
+       indexes []int // schema ordinal -> reflect struct field index
+}
+
+func inferStructLayout(t reflect.Type, path []reflect.Type) (*structLayout, 
error) {
+       if t.Kind() == reflect.Ptr {
+               t = t.Elem()
+       }
+       if t.Kind() != reflect.Struct || t == goDateType || t == goTimeType {
+               return nil, fmt.Errorf("row: schema inference expects a struct 
type, got %v", t)
+       }
+       for _, seen := range path {
+               if seen == t {
+                       return nil, fmt.Errorf("row: circular reference through 
type %v", t)
+               }
+       }
+       path = append(path, t)
+
+       type member struct {
+               lowerCamel string
+               goIndex    int
+               fieldType  reflect.Type
+       }
+       var members []member
+       for i := 0; i < t.NumField(); i++ {
+               f := t.Field(i)
+               if f.PkgPath != "" {
+                       continue
+               }
+               ignored, err := hasIgnoreTag(f.Tag.Get("fory"))
+               if err != nil {
+                       return nil, fmt.Errorf("%w (field %s of %v)", err, 
f.Name, t)
+               }
+               if ignored {
+                       continue
+               }
+               members = append(members, member{lowerFirst(f.Name), i, f.Type})
+       }
+       // Java sorts by the lowerCamel member name before converting names
+       // to snake_case; matching that order is required for schema and
+       // row-layout compatibility.
+       sort.Slice(members, func(a, b int) bool { return members[a].lowerCamel 
< members[b].lowerCamel })
+
+       layout := &structLayout{indexes: make([]int, 0, len(members))}
+       fields := make([]Field, 0, len(members))
+       for _, m := range members {
+               f, err := inferField(lowerCamelToLowerUnderscore(m.lowerCamel), 
m.fieldType, path)
+               if err != nil {
+                       return nil, fmt.Errorf("%w (field %s of %v)", err, 
t.Field(m.goIndex).Name, t)
+               }
+               fields = append(fields, f)
+               layout.indexes = append(layout.indexes, m.goIndex)
+       }
+       layout.schema = NewSchema(fields)
+       return layout, nil
+}
+
+func inferField(name string, t reflect.Type, path []reflect.Type) (Field, 
error) {
+       if t.Kind() == reflect.Ptr {
+               if t.Elem().Kind() == reflect.Ptr {
+                       return Field{}, fmt.Errorf("row: nested pointer type %v 
is unsupported", t)
+               }
+               inner, err := inferField(name, t.Elem(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               inner.Nullable = true
+               return inner, nil
+       }
+       switch t {
+       case goDateType:
+               return Field{Name: name, Type: Date32Type{}}, nil
+       case goTimeType:
+               return Field{Name: name, Type: TimestampType{}}, nil
+       case goDurationType:
+               return Field{Name: name, Type: DurationType{}}, nil
+       }
+       switch t.Kind() {
+       case reflect.Bool:
+               return Field{Name: name, Type: BoolType{}}, nil
+       case reflect.Int8:
+               return Field{Name: name, Type: Int8Type{}}, nil
+       case reflect.Int16:
+               return Field{Name: name, Type: Int16Type{}}, nil
+       case reflect.Int32:
+               return Field{Name: name, Type: Int32Type{}}, nil
+       case reflect.Int64, reflect.Int:
+               // `int` maps to int64 so the width never depends on the 
platform.
+               return Field{Name: name, Type: Int64Type{}}, nil
+       case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, 
reflect.Uint64, reflect.Uintptr:
+               return Field{}, fmt.Errorf("row: unsigned type %v is 
unsupported, use a signed type", t)
+       case reflect.Float32:
+               return Field{Name: name, Type: Float32Type{}}, nil
+       case reflect.Float64:
+               return Field{Name: name, Type: Float64Type{}}, nil
+       case reflect.String:
+               return Field{Name: name, Type: StringType{}, Nullable: true}, 
nil
+       case reflect.Slice:
+               if t.Elem().Kind() == reflect.Uint8 {
+                       return Field{Name: name, Type: BinaryType{}, Nullable: 
true}, nil
+               }
+               elem, err := inferField(listItemName, t.Elem(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               return Field{Name: name, Type: &ListType{Elem: elem}, Nullable: 
true}, nil
+       case reflect.Map:
+               if t.Key().Kind() == reflect.Ptr {
+                       return Field{}, fmt.Errorf("row: pointer map key type 
%v is unsupported", t)
+               }
+               key, err := inferField(mapKeyName, t.Key(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               key.Nullable = false
+               value, err := inferField(mapValueName, t.Elem(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               return Field{Name: name, Type: &MapType{Key: key, Value: 
value}, Nullable: true}, nil
+       case reflect.Struct:
+               layout, err := inferStructLayout(t, path)
+               if err != nil {
+                       return Field{}, err
+               }
+               return Field{Name: name, Type: &StructType{Fields: 
layout.schema.Fields()}, Nullable: true}, nil
+       default:
+               return Field{}, fmt.Errorf("row: type %v is unsupported in row 
format", t)
+       }
+}
+
+// hasIgnoreTag mirrors the ignore semantics of the core fory tag
+// parser (parseFieldTag in field_spec.go): a whole tag of "-" or an
+// ignore/ignore=true part skips the field, ignore=false keeps it, and
+// any other ignore value is an error. Other tag keys are not used by
+// the row format.
+func hasIgnoreTag(tag string) (bool, error) {
+       if tag == "-" {
+               return true, nil
+       }
+       ignore := false
+       for _, part := range strings.Split(tag, ",") {
+               part = strings.TrimSpace(part)
+               if part == "ignore" {
+                       ignore = true
+               } else if strings.HasPrefix(part, "ignore=") {
+                       switch strings.TrimPrefix(part, "ignore=") {
+                       case "true":

Review Comment:
   **[Suggestion]** `hasIgnoreTag` accepts only literal `"true"`/`"false"` 
while the core tag parser `parseFieldTag` delegates to `parseBoolStrict`, which 
accepts `true/1/yes/false/0/no` case-insensitively with trimming. The doc 
comment claims this function mirrors the core parser. — Failure scenario: a 
struct tagged `fory:"ignore=1"` serializes correctly through the core fory 
serializer, but `InferSchema` returns an error for the same tag.
   
   ```suggestion
                } else if strings.HasPrefix(part, "ignore=") {
                        switch 
strings.ToLower(strings.TrimSpace(strings.TrimPrefix(part, "ignore="))) {
                        case "true", "1", "yes":
   ```
   
   _— Qwen3-235B-A22B via Qwen Code /review_



##########
go/fory/row/row.go:
##########
@@ -0,0 +1,370 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package row
+
+import (
+       "encoding/binary"
+       "fmt"
+       "math"
+       "time"
+
+       fory "github.com/apache/fory/go/fory"
+)
+
+// Row is a zero-copy reader over one row's bytes. Getters read directly
+// from the underlying data without deserializing other fields; nested
+// values are sub-slice views, never copies (except String).
+//
+// Fixed-width getters return the zero value for null fields; use
+// IsNullAt to distinguish. Variable-width getters return nil (or "")
+// for null fields. An out-of-range field index panics; offsets in
+// corrupt or untrusted data may panic on slice bounds, so wrap
+// untrusted decoding with recover.
+type Row struct {
+       fields      []Field
+       data        []byte
+       bitmapWidth int
+}
+
+func NewRow(schema *Schema, data []byte) *Row {
+       return newRow(schema.Fields(), data)
+}
+
+func newRow(fields []Field, data []byte) *Row {
+       return &Row{fields: fields, data: data, bitmapWidth: 
bitmapWidthInBytes(len(fields))}
+}
+
+func (r *Row) NumFields() int { return len(r.fields) }
+func (r *Row) SizeBytes() int { return len(r.data) }
+
+// Data returns the underlying row bytes; callers must not modify them.
+func (r *Row) Data() []byte { return r.data }
+
+func (r *Row) IsNullAt(i int) bool {
+       if uint(i) >= uint(len(r.fields)) {
+               panic(fmt.Sprintf("row: field index %d out of range [0, %d)", 
i, len(r.fields)))
+       }
+       return getBit(r.data, i)
+}
+
+func (r *Row) slot(i int) int { return r.bitmapWidth + i*8 }
+
+func (r *Row) Bool(i int) bool {
+       return !r.IsNullAt(i) && r.data[r.slot(i)] != 0
+}
+
+func (r *Row) Int8(i int) int8 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return int8(r.data[r.slot(i)])
+}
+
+func (r *Row) Int16(i int) int16 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return int16(binary.LittleEndian.Uint16(r.data[r.slot(i):]))
+}
+
+func (r *Row) Int32(i int) int32 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return int32(binary.LittleEndian.Uint32(r.data[r.slot(i):]))
+}
+
+func (r *Row) Int64(i int) int64 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return int64(binary.LittleEndian.Uint64(r.data[r.slot(i):]))
+}
+
+func (r *Row) Float32(i int) float32 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return 
math.Float32frombits(binary.LittleEndian.Uint32(r.data[r.slot(i):]))
+}
+
+func (r *Row) Float64(i int) float64 {
+       if r.IsNullAt(i) {
+               return 0
+       }
+       return 
math.Float64frombits(binary.LittleEndian.Uint64(r.data[r.slot(i):]))
+}
+
+func (r *Row) Date(i int) fory.Date {
+       if r.IsNullAt(i) {
+               return fory.Date{}
+       }
+       return 
dateFromDays(int32(binary.LittleEndian.Uint32(r.data[r.slot(i):])))
+}
+
+func (r *Row) Timestamp(i int) time.Time {
+       if r.IsNullAt(i) {
+               return time.Time{}
+       }
+       return time.UnixMicro(r.Int64(i))
+}
+
+func (r *Row) Duration(i int) time.Duration {
+       return time.Duration(r.Int64(i)) * time.Microsecond
+}
+
+// varData returns the value bytes of variable-width field i, or nil if
+// the field is null. An empty value returns an empty non-nil slice.
+func (r *Row) varData(i int) []byte {
+       if r.IsNullAt(i) {
+               return nil
+       }
+       offset, size := 
decodeOffsetAndSize(binary.LittleEndian.Uint64(r.data[r.slot(i):]))
+       return boundedSlice(r.data, offset, size)
+}
+
+// Binary returns a zero-copy view of field i's bytes.
+func (r *Row) Binary(i int) []byte { return r.varData(i) }
+
+func (r *Row) String(i int) string { return string(r.varData(i)) }
+
+func (r *Row) Struct(i int) *Row {
+       data := r.varData(i)
+       if data == nil {
+               return nil
+       }
+       structType := r.fields[i].Type.(*StructType)
+       return newRow(structType.Fields, data)
+}
+
+func (r *Row) Array(i int) *ArrayData {
+       data := r.varData(i)
+       if data == nil {
+               return nil
+       }
+       listType := r.fields[i].Type.(*ListType)
+       return NewArrayData(listType.Elem, data)
+}
+
+func (r *Row) Map(i int) *MapData {
+       data := r.varData(i)
+       if data == nil {
+               return nil
+       }
+       return NewMapData(r.fields[i].Type.(*MapType), data)
+}
+
+// ArrayData is a zero-copy reader over one array's bytes, with the same
+// null and bounds semantics as Row.
+type ArrayData struct {
+       elem        Field
+       data        []byte
+       numElements int
+       elemSize    int
+       headerBytes int
+}
+
+func NewArrayData(elem Field, data []byte) *ArrayData {
+       numElements := int(binary.LittleEndian.Uint64(data))
+       elemSize := elem.Type.ByteWidth()
+       if elemSize < 0 {
+               elemSize = 8
+       }
+       return &ArrayData{
+               elem:        elem,
+               data:        data,
+               numElements: numElements,
+               elemSize:    elemSize,
+               headerBytes: 8 + bitmapWidthInBytes(numElements),
+       }
+}
+
+func (a *ArrayData) NumElements() int { return a.numElements }
+func (a *ArrayData) SizeBytes() int   { return len(a.data) }
+
+// validateBounds rejects arrays whose declared element count is not
+// covered by the available bytes, so decoders can check before
+// allocating from an attacker-declared count.
+func (a *ArrayData) validateBounds() error {
+       // The coarse count check involves no arithmetic, so it cannot be
+       // defeated by overflow: every element occupies at least one data
+       // byte. It also bounds numElements low enough that headerBytes
+       // (computed in NewArrayData) and the product below are exact.
+       if a.numElements < 0 || a.numElements > len(a.data) {
+               return fmt.Errorf("row: array declares %d elements but holds 
only %d bytes", a.numElements, len(a.data))
+       }
+       need := int64(a.headerBytes) + int64(a.numElements)*int64(a.elemSize)
+       if need > int64(len(a.data)) {
+               return fmt.Errorf("row: array declares %d elements needing %d 
bytes but holds only %d", a.numElements, need, len(a.data))
+       }
+       return nil
+}
+
+func (a *ArrayData) IsNullAt(i int) bool {
+       if uint(i) >= uint(a.numElements) {
+               panic(fmt.Sprintf("row: array index %d out of range [0, %d)", 
i, a.numElements))
+       }
+       return getBit(a.data[8:a.headerBytes], i)
+}
+
+func (a *ArrayData) slot(i int) int { return a.headerBytes + i*a.elemSize }
+
+func (a *ArrayData) Bool(i int) bool {
+       return !a.IsNullAt(i) && a.data[a.slot(i)] != 0
+}
+
+func (a *ArrayData) Int8(i int) int8 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return int8(a.data[a.slot(i)])
+}
+
+func (a *ArrayData) Int16(i int) int16 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return int16(binary.LittleEndian.Uint16(a.data[a.slot(i):]))
+}
+
+func (a *ArrayData) Int32(i int) int32 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return int32(binary.LittleEndian.Uint32(a.data[a.slot(i):]))
+}
+
+func (a *ArrayData) Int64(i int) int64 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return int64(binary.LittleEndian.Uint64(a.data[a.slot(i):]))
+}
+
+func (a *ArrayData) Float32(i int) float32 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return 
math.Float32frombits(binary.LittleEndian.Uint32(a.data[a.slot(i):]))
+}
+
+func (a *ArrayData) Float64(i int) float64 {
+       if a.IsNullAt(i) {
+               return 0
+       }
+       return 
math.Float64frombits(binary.LittleEndian.Uint64(a.data[a.slot(i):]))
+}
+
+func (a *ArrayData) Date(i int) fory.Date {
+       if a.IsNullAt(i) {
+               return fory.Date{}
+       }
+       return 
dateFromDays(int32(binary.LittleEndian.Uint32(a.data[a.slot(i):])))
+}
+
+func (a *ArrayData) Timestamp(i int) time.Time {
+       if a.IsNullAt(i) {
+               return time.Time{}
+       }
+       return time.UnixMicro(a.Int64(i))
+}
+
+func (a *ArrayData) Duration(i int) time.Duration {
+       return time.Duration(a.Int64(i)) * time.Microsecond
+}
+
+func (a *ArrayData) varData(i int) []byte {
+       if a.IsNullAt(i) {
+               return nil
+       }
+       offset, size := 
decodeOffsetAndSize(binary.LittleEndian.Uint64(a.data[a.slot(i):]))
+       return boundedSlice(a.data, offset, size)
+}
+
+// Binary returns a zero-copy view of element i's bytes.
+func (a *ArrayData) Binary(i int) []byte { return a.varData(i) }
+
+func (a *ArrayData) String(i int) string { return string(a.varData(i)) }
+
+func (a *ArrayData) Struct(i int) *Row {
+       data := a.varData(i)
+       if data == nil {
+               return nil
+       }
+       return newRow(a.elem.Type.(*StructType).Fields, data)
+}
+
+func (a *ArrayData) Array(i int) *ArrayData {
+       data := a.varData(i)
+       if data == nil {
+               return nil
+       }
+       return NewArrayData(a.elem.Type.(*ListType).Elem, data)
+}
+
+func (a *ArrayData) Map(i int) *MapData {
+       data := a.varData(i)
+       if data == nil {
+               return nil
+       }
+       return NewMapData(a.elem.Type.(*MapType), data)
+}
+
+// MapData is a zero-copy reader over one map's bytes: the keys array
+// and values array views share the map's underlying data.
+type MapData struct {
+       keys   *ArrayData
+       values *ArrayData
+}
+
+func NewMapData(mapType *MapType, data []byte) *MapData {
+       keysSize := int(binary.LittleEndian.Uint64(data))
+       keysData := boundedSlice(data, 8, keysSize)
+       valuesData := boundedSlice(data, 8+keysSize, len(data)-8-keysSize)
+       return &MapData{
+               keys:   NewArrayData(mapType.Key, keysData),
+               values: NewArrayData(mapType.Value, valuesData),
+       }
+}
+
+// boundedSlice checks declared bounds against the data LENGTH
+// and caps the view so nested
+// readers cannot reach outside it either. Out-of-bounds panics are
+// converted to errors by the encoder's decode entry points.
+func boundedSlice(data []byte, offset, size int) []byte {
+       end := offset + size
+       if offset < 0 || size < 0 || end > len(data) {

Review Comment:
   **[Suggestion]** `boundedSlice`'s bounds check is defeated by signed integer 
overflow: `end := offset + size` wraps negative when `size` is near `MaxInt64` 
(reachable via `NewMapData`'s attacker-controlled uint64→int cast). All three 
guards pass on the negative `end`, and the function reaches a generic runtime 
panic instead of the intended descriptive one. Go's runtime prevents 
memory-safety issues, but the defensive boundary is silently bypassed. — 
Failure scenario: a crafted `keysSize = MaxInt64` makes `end = 8 + MaxInt64` 
overflow to negative; `data[8:negative]` triggers an uninformative panic.
   
   ```suggestion
        end := offset + size
        if offset < 0 || size < 0 || end < offset || end > len(data) {
   ```
   
   _— Qwen3-235B-A22B via Qwen Code /review_



##########
go/fory/row/infer.go:
##########
@@ -0,0 +1,252 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package row
+
+import (
+       "fmt"
+       "reflect"
+       "sort"
+       "strings"
+       "time"
+       "unicode"
+       "unicode/utf8"
+
+       fory "github.com/apache/fory/go/fory"
+)
+
+var (
+       goDateType     = reflect.TypeOf(fory.Date{})
+       goTimeType     = reflect.TypeOf(time.Time{})
+       goDurationType = reflect.TypeOf(time.Duration(0))
+)
+
+// InferSchema infers the row schema for a struct type or pointer to
+// struct, including every exported field not tagged `fory:"ignore"`.
+//
+// Fields are sorted by their lowerCamel name and named by its
+// snake_case form (UserName -> user_name), matching Java's schema
+// inference so both languages derive identical schemas.
+//
+// Type mapping:
+//   - bool, int8/16/32/64, float32/64: same-width row types; int maps to int64
+//   - string, []byte: string and binary, nullable
+//   - slices, maps, nested structs: list, map, and struct, nullable
+//   - *T: the row type of T, nullable
+//   - fory.Date, time.Time, time.Duration: date32, timestamp, duration
+//
+// Unsigned integers, fixed-size arrays, nested pointers, and pointer
+// map keys are unsupported and return an error.
+func InferSchema(t reflect.Type) (*Schema, error) {
+       layout, err := inferStructLayout(t, nil)
+       if err != nil {
+               return nil, err
+       }
+       return layout.schema, nil
+}
+
+// structLayout maps schema ordinals back to Go struct field indexes.
+type structLayout struct {
+       schema  *Schema
+       indexes []int // schema ordinal -> reflect struct field index
+}
+
+func inferStructLayout(t reflect.Type, path []reflect.Type) (*structLayout, 
error) {
+       if t.Kind() == reflect.Ptr {
+               t = t.Elem()
+       }
+       if t.Kind() != reflect.Struct || t == goDateType || t == goTimeType {
+               return nil, fmt.Errorf("row: schema inference expects a struct 
type, got %v", t)
+       }
+       for _, seen := range path {
+               if seen == t {
+                       return nil, fmt.Errorf("row: circular reference through 
type %v", t)
+               }
+       }
+       path = append(path, t)
+
+       type member struct {
+               lowerCamel string
+               goIndex    int
+               fieldType  reflect.Type
+       }
+       var members []member
+       for i := 0; i < t.NumField(); i++ {
+               f := t.Field(i)
+               if f.PkgPath != "" {
+                       continue
+               }
+               ignored, err := hasIgnoreTag(f.Tag.Get("fory"))
+               if err != nil {
+                       return nil, fmt.Errorf("%w (field %s of %v)", err, 
f.Name, t)
+               }
+               if ignored {
+                       continue
+               }
+               members = append(members, member{lowerFirst(f.Name), i, f.Type})
+       }
+       // Java sorts by the lowerCamel member name before converting names
+       // to snake_case; matching that order is required for schema and
+       // row-layout compatibility.
+       sort.Slice(members, func(a, b int) bool { return members[a].lowerCamel 
< members[b].lowerCamel })
+
+       layout := &structLayout{indexes: make([]int, 0, len(members))}
+       fields := make([]Field, 0, len(members))
+       for _, m := range members {
+               f, err := inferField(lowerCamelToLowerUnderscore(m.lowerCamel), 
m.fieldType, path)
+               if err != nil {
+                       return nil, fmt.Errorf("%w (field %s of %v)", err, 
t.Field(m.goIndex).Name, t)
+               }
+               fields = append(fields, f)
+               layout.indexes = append(layout.indexes, m.goIndex)
+       }
+       layout.schema = NewSchema(fields)
+       return layout, nil
+}
+
+func inferField(name string, t reflect.Type, path []reflect.Type) (Field, 
error) {
+       if t.Kind() == reflect.Ptr {
+               if t.Elem().Kind() == reflect.Ptr {
+                       return Field{}, fmt.Errorf("row: nested pointer type %v 
is unsupported", t)
+               }
+               inner, err := inferField(name, t.Elem(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               inner.Nullable = true
+               return inner, nil
+       }
+       switch t {
+       case goDateType:
+               return Field{Name: name, Type: Date32Type{}}, nil
+       case goTimeType:
+               return Field{Name: name, Type: TimestampType{}}, nil
+       case goDurationType:
+               return Field{Name: name, Type: DurationType{}}, nil
+       }
+       switch t.Kind() {
+       case reflect.Bool:
+               return Field{Name: name, Type: BoolType{}}, nil
+       case reflect.Int8:
+               return Field{Name: name, Type: Int8Type{}}, nil
+       case reflect.Int16:
+               return Field{Name: name, Type: Int16Type{}}, nil
+       case reflect.Int32:
+               return Field{Name: name, Type: Int32Type{}}, nil
+       case reflect.Int64, reflect.Int:
+               // `int` maps to int64 so the width never depends on the 
platform.
+               return Field{Name: name, Type: Int64Type{}}, nil
+       case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, 
reflect.Uint64, reflect.Uintptr:
+               return Field{}, fmt.Errorf("row: unsigned type %v is 
unsupported, use a signed type", t)
+       case reflect.Float32:
+               return Field{Name: name, Type: Float32Type{}}, nil
+       case reflect.Float64:
+               return Field{Name: name, Type: Float64Type{}}, nil
+       case reflect.String:
+               return Field{Name: name, Type: StringType{}, Nullable: true}, 
nil
+       case reflect.Slice:
+               if t.Elem().Kind() == reflect.Uint8 {
+                       return Field{Name: name, Type: BinaryType{}, Nullable: 
true}, nil
+               }
+               elem, err := inferField(listItemName, t.Elem(), path)
+               if err != nil {
+                       return Field{}, err
+               }
+               return Field{Name: name, Type: &ListType{Elem: elem}, Nullable: 
true}, nil

Review Comment:
   **[Suggestion]** `inferField` leaves the list-element `Nullable` flag at its 
zero value `false` for value-type elements (e.g. `[]int32`), diverging from 
Java's `TypeInference` (which produces `Nullable: true` for `List<Integer>`) 
and Go's own `List()`/`Map()` factories (which always set `Nullable: true`). 
The nullable flag is encoded as bit 6 of the field header in `SchemaToBytes`, 
so schema bytes differ. The cross-language test fixture uses only pointer 
elements (`[]*string`), masking this divergence. — Failure scenario: adding a 
`[]int32` field to the xlang fixture would fail both 
`parsed.Equal(encoder.Schema())` and `bytes.Equal(reencoded, schemaBytes)`.
   
   ```suggestion
                elem, err := inferField(listItemName, t.Elem(), path)
                if err != nil {
                        return Field{}, err
                }
                elem.Nullable = true
                return Field{Name: name, Type: &ListType{Elem: elem}, Nullable: 
true}, nil
   ```
   
   _— Qwen3-235B-A22B via Qwen Code /review_



##########
go/fory/row/encoder.go:
##########
@@ -0,0 +1,490 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package row
+
+import (
+       "encoding/binary"
+       "fmt"
+       "reflect"
+       "time"
+
+       fory "github.com/apache/fory/go/fory"
+)
+
+// Encoder converts values of struct type T to and from row bytes using
+// a codec tree compiled once with reflection at construction time. The
+// schema is inferred per InferSchema.
+//
+// An Encoder owns a reusable write buffer and is NOT goroutine-safe;
+// create one Encoder per goroutine. Decoding is safe on corrupt or
+// untrusted input.
+type Encoder[T any] struct {
+       codec *structCodec
+       hash  int64
+       buf   *fory.ByteBuffer
+}
+
+func NewEncoder[T any]() (*Encoder[T], error) {
+       t := reflect.TypeOf((*T)(nil)).Elem()
+       if t.Kind() != reflect.Struct {
+               return nil, fmt.Errorf("row: Encoder requires a struct type, 
got %v", t)
+       }
+       buf := fory.NewByteBuffer(nil)
+       codec, err := newStructCodec(t, buf)
+       if err != nil {
+               return nil, err
+       }
+       return &Encoder[T]{codec: codec, hash: ComputeSchemaHash(codec.schema), 
buf: buf}, nil
+}
+
+func (e *Encoder[T]) Schema() *Schema { return e.codec.schema }
+
+// SchemaHash returns the cross-language schema hash used by Encode and
+// Decode to detect out-of-sync struct definitions.
+func (e *Encoder[T]) SchemaHash() int64 { return e.hash }
+
+// ToRow serializes v to row bytes (no framing, just the row).
+func (e *Encoder[T]) ToRow(v *T) ([]byte, error) {
+       e.buf.SetWriterIndex(0)
+       if err := e.codec.writeStruct(reflect.ValueOf(v).Elem()); err != nil {
+               return nil, err
+       }
+       out := make([]byte, e.buf.WriterIndex())
+       copy(out, e.buf.GetData()[:e.buf.WriterIndex()])
+       return out, nil
+}
+
+// FromRow deserializes row bytes produced with this schema.
+func (e *Encoder[T]) FromRow(data []byte) (T, error) {
+       var out T
+       err := e.FromRowInto(data, &out)
+       return out, err
+}
+
+func (e *Encoder[T]) FromRowInto(data []byte, out *T) (err error) {
+       defer func() {
+               if p := recover(); p != nil {
+                       err = fmt.Errorf("row: corrupt row data: %v", p)
+               }
+       }()
+       return e.codec.readStruct(NewRow(e.codec.schema, data), 
reflect.ValueOf(out).Elem())
+}
+
+// Encode frames the row for cross-language exchange: an int64
+// little-endian schema hash followed by the row bytes, matching the
+// Java and Python row encoders.
+func (e *Encoder[T]) Encode(v *T) ([]byte, error) {
+       rowBytes, err := e.ToRow(v)
+       if err != nil {
+               return nil, err
+       }
+       out := make([]byte, 8+len(rowBytes))
+       binary.LittleEndian.PutUint64(out, uint64(e.hash))
+       copy(out[8:], rowBytes)
+       return out, nil
+}
+
+// Decode verifies the schema hash and deserializes the row.
+func (e *Encoder[T]) Decode(data []byte) (T, error) {
+       var out T
+       if len(data) < 8 {
+               return out, fmt.Errorf("row: encoded data of %d bytes is too 
short for the schema hash", len(data))
+       }
+       hash := int64(binary.LittleEndian.Uint64(data))
+       if hash != e.hash {
+               return out, fmt.Errorf("row: schema hash mismatch: data has %d, 
encoder expects %d; writer and reader struct definitions are out of sync", 
hash, e.hash)
+       }
+       err := e.FromRowInto(data[8:], &out)
+       return out, err
+}
+
+// slotWriter is the shared write surface of RowWriter and ArrayWriter,
+// letting one value codec serve struct fields and array elements.
+type slotWriter interface {
+       SetNullAt(i int)
+       WriteBool(i int, v bool)
+       WriteInt8(i int, v int8)
+       WriteInt16(i int, v int16)
+       WriteInt32(i int, v int32)
+       WriteInt64(i int, v int64)
+       WriteFloat32(i int, v float32)
+       WriteFloat64(i int, v float64)
+       WriteDate(i int, d fory.Date) error
+       WriteTimestamp(i int, t time.Time)
+       WriteDuration(i int, d time.Duration)
+       WriteString(i int, s string) error
+       WriteBytes(i int, b []byte) error
+       SetOffsetAndSize(i, absStart, size int) error
+}
+
+// valueReader is the shared read surface of Row and ArrayData.
+type valueReader interface {
+       IsNullAt(i int) bool
+       Bool(i int) bool
+       Int8(i int) int8
+       Int16(i int) int16
+       Int32(i int) int32
+       Int64(i int) int64
+       Float32(i int) float32
+       Float64(i int) float64
+       Date(i int) fory.Date
+       Timestamp(i int) time.Time
+       Duration(i int) time.Duration
+       String(i int) string
+       Binary(i int) []byte
+       Struct(i int) *Row
+       Array(i int) *ArrayData
+       Map(i int) *MapData
+}
+
+// valueCodec reads or writes one value at slot/element i. Write
+// functions handle nil for nilable Go types; read functions overwrite
+// the target even when the field is null, so reused targets stay clean.
+type valueCodec struct {
+       write func(w slotWriter, i int, v reflect.Value) error
+       read  func(g valueReader, i int, v reflect.Value) error
+}
+
+// structCodec writes and reads one struct level; nested structs hold
+// their own child codec with a child RowWriter sharing the buffer.
+type structCodec struct {
+       schema *Schema
+       writer *RowWriter
+       fields []fieldCodec
+}
+
+type fieldCodec struct {
+       goIndex int
+       codec   valueCodec
+}
+
+func newStructCodec(t reflect.Type, buf *fory.ByteBuffer) (*structCodec, 
error) {
+       layout, err := inferStructLayout(t, nil)
+       if err != nil {
+               return nil, err
+       }
+       sc := &structCodec{
+               schema: layout.schema,
+               writer: NewRowWriterWithBuffer(layout.schema, buf),
+               fields: make([]fieldCodec, 0, layout.schema.NumFields()),
+       }
+       for ordinal, goIndex := range layout.indexes {
+               codec, err := newValueCodec(t.Field(goIndex).Type, 
layout.schema.Field(ordinal).Type, buf)
+               if err != nil {
+                       return nil, err
+               }
+               sc.fields = append(sc.fields, fieldCodec{goIndex: goIndex, 
codec: codec})
+       }
+       return sc, nil
+}
+
+func (sc *structCodec) writeStruct(v reflect.Value) error {
+       sc.writer.Reset()
+       for ordinal := range sc.fields {
+               fc := &sc.fields[ordinal]
+               if err := fc.codec.write(sc.writer, ordinal, 
v.Field(fc.goIndex)); err != nil {
+                       return err
+               }
+       }
+       return nil
+}
+
+func (sc *structCodec) readStruct(r *Row, v reflect.Value) error {
+       for ordinal := range sc.fields {
+               fc := &sc.fields[ordinal]
+               if err := fc.codec.read(r, ordinal, v.Field(fc.goIndex)); err 
!= nil {
+                       return err
+               }
+       }
+       return nil
+}
+
+func newValueCodec(goType reflect.Type, dataType DataType, buf 
*fory.ByteBuffer) (valueCodec, error) {
+       if goType.Kind() == reflect.Ptr {
+               elemType := goType.Elem()
+               inner, err := newValueCodec(elemType, dataType, buf)
+               if err != nil {
+                       return valueCodec{}, err
+               }
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{
+                               if v.IsNil() {
+                                       w.SetNullAt(i)
+                                       return nil
+                               }
+                               return inner.write(w, i, v.Elem())
+                       },
+                       read: func(g valueReader, i int, v reflect.Value) error 
{
+                               if g.IsNullAt(i) {
+                                       v.Set(reflect.Zero(goType))
+                                       return nil
+                               }
+                               p := reflect.New(elemType)
+                               if err := inner.read(g, i, p.Elem()); err != 
nil {
+                                       return err
+                               }
+                               v.Set(p)
+                               return nil
+                       },
+               }, nil
+       }
+
+       switch dt := dataType.(type) {
+       case BoolType:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteBool(i, v.Bool()); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetBool(g.Bool(i)); return nil },
+               }, nil
+       case Int8Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteInt8(i, int8(v.Int())); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetInt(int64(g.Int8(i))); return nil },
+               }, nil
+       case Int16Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteInt16(i, int16(v.Int())); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetInt(int64(g.Int16(i))); return nil },
+               }, nil
+       case Int32Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteInt32(i, int32(v.Int())); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetInt(int64(g.Int32(i))); return nil },
+               }, nil
+       case Int64Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteInt64(i, v.Int()); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetInt(g.Int64(i)); return nil },
+               }, nil
+       case Float32Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteFloat32(i, float32(v.Float())); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetFloat(float64(g.Float32(i))); return nil },
+               }, nil
+       case Float64Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ w.WriteFloat64(i, v.Float()); return nil },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetFloat(g.Float64(i)); return nil },
+               }, nil
+       case Date32Type:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ return w.WriteDate(i, v.Interface().(fory.Date)) },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.Set(reflect.ValueOf(g.Date(i))); return nil },
+               }, nil
+       case TimestampType:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{
+                               w.WriteTimestamp(i, v.Interface().(time.Time))
+                               return nil
+                       },
+                       read: func(g valueReader, i int, v reflect.Value) error 
{ v.Set(reflect.ValueOf(g.Timestamp(i))); return nil },
+               }, nil
+       case DurationType:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{
+                               w.WriteDuration(i, time.Duration(v.Int()))
+                               return nil
+                       },
+                       read: func(g valueReader, i int, v reflect.Value) error 
{ v.SetInt(int64(g.Duration(i))); return nil },
+               }, nil
+       case StringType:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{ return w.WriteString(i, v.String()) },
+                       read:  func(g valueReader, i int, v reflect.Value) 
error { v.SetString(g.String(i)); return nil },
+               }, nil
+       case BinaryType:
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{
+                               if v.IsNil() {
+                                       w.SetNullAt(i)
+                                       return nil
+                               }
+                               return w.WriteBytes(i, v.Bytes())
+                       },
+                       read: func(g valueReader, i int, v reflect.Value) error 
{
+                               b := g.Binary(i)
+                               if b == nil {
+                                       v.SetBytes(nil)
+                                       return nil
+                               }
+                               // Copy so the decoded struct never aliases the 
input.
+                               owned := make([]byte, len(b))
+                               copy(owned, b)
+                               v.SetBytes(owned)
+                               return nil
+                       },
+               }, nil
+       case *ListType:
+               return newListCodec(goType, dt, buf)
+       case *MapType:
+               return newMapCodec(goType, dt, buf)
+       case *StructType:
+               child, err := newStructCodec(goType, buf)
+               if err != nil {
+                       return valueCodec{}, err
+               }
+               return valueCodec{
+                       write: func(w slotWriter, i int, v reflect.Value) error 
{
+                               start := child.writer.buf.WriterIndex()
+                               if err := child.writeStruct(v); err != nil {
+                                       return err
+                               }
+                               return w.SetOffsetAndSize(i, start, 
child.writer.buf.WriterIndex()-start)
+                       },
+                       read: func(g valueReader, i int, v reflect.Value) error 
{
+                               nested := g.Struct(i)
+                               if nested == nil {
+                                       v.Set(reflect.Zero(goType))
+                                       return nil
+                               }
+                               return child.readStruct(nested, v)
+                       },
+               }, nil
+       default:
+               return valueCodec{}, fmt.Errorf("row: data type %s is not 
supported by the encoder", dataType)
+       }
+}
+
+func newListCodec(goType reflect.Type, listType *ListType, buf 
*fory.ByteBuffer) (valueCodec, error) {
+       elemCodec, err := newValueCodec(goType.Elem(), listType.Elem.Type, buf)
+       if err != nil {
+               return valueCodec{}, err
+       }
+       writer := NewArrayWriter(listType.Elem, buf)
+       return valueCodec{
+               write: func(w slotWriter, i int, v reflect.Value) error {
+                       if v.IsNil() {
+                               w.SetNullAt(i)
+                               return nil
+                       }
+                       n := v.Len()
+                       start := buf.WriterIndex()
+                       if err := writer.Reset(n); err != nil {
+                               return err
+                       }
+                       for j := 0; j < n; j++ {
+                               if err := elemCodec.write(writer, j, 
v.Index(j)); err != nil {
+                                       return err
+                               }
+                       }
+                       return w.SetOffsetAndSize(i, start, 
buf.WriterIndex()-start)
+               },
+               read: func(g valueReader, i int, v reflect.Value) error {
+                       arr := g.Array(i)
+                       if arr == nil {
+                               v.Set(reflect.Zero(goType))
+                               return nil
+                       }
+                       if err := arr.validateBounds(); err != nil {
+                               return err
+                       }
+                       n := arr.NumElements()
+                       s := reflect.MakeSlice(goType, n, n)
+                       for j := 0; j < n; j++ {
+                               if err := elemCodec.read(arr, j, s.Index(j)); 
err != nil {
+                                       return err
+                               }
+                       }
+                       v.Set(s)
+                       return nil
+               },
+       }, nil
+}
+
+func newMapCodec(goType reflect.Type, mapType *MapType, buf *fory.ByteBuffer) 
(valueCodec, error) {
+       keyCodec, err := newValueCodec(goType.Key(), mapType.Key.Type, buf)
+       if err != nil {
+               return valueCodec{}, err
+       }
+       valueCodecImpl, err := newValueCodec(goType.Elem(), mapType.Value.Type, 
buf)
+       if err != nil {
+               return valueCodec{}, err
+       }
+       mapWriter := NewMapWriter(buf)
+       keysWriter := NewArrayWriter(mapType.Key, buf)
+       valuesWriter := NewArrayWriter(mapType.Value, buf)
+       return valueCodec{
+               write: func(w slotWriter, i int, v reflect.Value) error {
+                       if v.IsNil() {
+                               w.SetNullAt(i)
+                               return nil
+                       }
+                       n := v.Len()
+                       start := buf.WriterIndex()
+                       mapWriter.Reset()
+                       // Go map iteration order changes between iterations, so
+                       // snapshot entries once to keep keys and values 
aligned.
+                       keys := make([]reflect.Value, 0, n)
+                       values := make([]reflect.Value, 0, n)
+                       iter := v.MapRange()
+                       for iter.Next() {
+                               keys = append(keys, iter.Key())
+                               values = append(values, iter.Value())
+                       }
+                       if err := keysWriter.Reset(len(keys)); err != nil {
+                               return err
+                       }
+                       for j, k := range keys {
+                               if err := keyCodec.write(keysWriter, j, k); err 
!= nil {
+                                       return err
+                               }
+                       }
+                       mapWriter.FinishKeys()
+                       if err := valuesWriter.Reset(len(values)); err != nil {
+                               return err
+                       }
+                       for j, val := range values {
+                               if err := valueCodecImpl.write(valuesWriter, j, 
val); err != nil {
+                                       return err
+                               }
+                       }
+                       return w.SetOffsetAndSize(i, start, 
buf.WriterIndex()-start)
+               },
+               read: func(g valueReader, i int, v reflect.Value) error {
+                       md := g.Map(i)
+                       if md == nil {
+                               v.Set(reflect.Zero(goType))
+                               return nil
+                       }
+                       keys, values := md.Keys(), md.Values()
+                       if err := keys.validateBounds(); err != nil {
+                               return err
+                       }
+                       if err := values.validateBounds(); err != nil {
+                               return err
+                       }
+                       n := keys.NumElements()
+                       if values.NumElements() != n {
+                               return fmt.Errorf("row: map has %d keys but %d 
values", n, values.NumElements())
+                       }
+                       m := reflect.MakeMapWithSize(goType, n)
+                       for j := 0; j < n; j++ {
+                               key := reflect.New(goType.Key()).Elem()
+                               if err := keyCodec.read(keys, j, key); err != 
nil {
+                                       return err
+                               }
+                               value := reflect.New(goType.Elem()).Elem()

Review Comment:
   **[Suggestion]** `newMapCodec`'s read loop allocates two heap objects per 
map entry via `reflect.New(...).Elem()` inside the loop. Since `SetMapIndex` 
copies the key and value, and the read functions fully overwrite their targets 
(per the `valueCodec` doc contract), both allocations can be hoisted before the 
loop. — Concrete cost: deserializing a map with N entries performs 2N 
short-lived heap allocations that immediately become garbage, adding GC 
pressure proportional to map size.
   
   ```suggestion
                        key := reflect.New(goType.Key()).Elem()
                        value := reflect.New(goType.Elem()).Elem()
                        for j := 0; j < n; j++ {
                                if err := keyCodec.read(keys, j, key); err != 
nil {
                                        return err
                                }
   ```
   
   _— Qwen3-235B-A22B via Qwen Code /review_



##########
go/fory/row/writer.go:
##########
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package row
+
+import (
+       "encoding/binary"
+       "fmt"
+       "math"
+       "time"
+
+       fory "github.com/apache/fory/go/fory"
+)
+
+const maxArrayDataBytes = math.MaxInt32 - 15
+
+// RowWriter writes one row into a ByteBuffer: null bitmap, fixed 8-byte
+// field slots, then the variable data region. All slot and bitmap
+// offsets are relative to the row base, so a nested RowWriter can share
+// the parent's buffer and produce a self-contained row.
+//
+// Reset rebases the writer at the buffer's current writer index and must
+// be called before writing each row. Writers are not goroutine-safe.
+type RowWriter struct {
+       schema      *Schema
+       buf         *fory.ByteBuffer
+       base        int
+       numFields   int
+       bitmapWidth int
+       fixedSize   int
+}
+
+func NewRowWriter(schema *Schema) *RowWriter {
+       return NewRowWriterWithBuffer(schema, fory.NewByteBuffer(nil))
+}
+
+// NewRowWriterWithBuffer shares an existing buffer, e.g. to write a
+// nested struct row into its parent's variable data region.
+func NewRowWriterWithBuffer(schema *Schema, buf *fory.ByteBuffer) *RowWriter {
+       n := schema.NumFields()
+       bitmapWidth := bitmapWidthInBytes(n)
+       return &RowWriter{
+               schema:      schema,
+               buf:         buf,
+               numFields:   n,
+               bitmapWidth: bitmapWidth,
+               fixedSize:   bitmapWidth + n*8,
+       }
+}
+
+func (w *RowWriter) Schema() *Schema          { return w.schema }
+func (w *RowWriter) Buffer() *fory.ByteBuffer { return w.buf }
+
+// Reset rebases the writer at the current writer index and zeroes the
+// whole fixed region. The buffer reuses dirty capacity after shrinking,
+// so zeroing here is what makes null slots and padding deterministic;
+// it also lets narrow fixed-width writes store just the value.
+func (w *RowWriter) Reset() {
+       w.base = w.buf.WriterIndex()
+       w.buf.Reserve(w.fixedSize)
+       data := w.buf.GetData()
+       clear(data[w.base : w.base+w.fixedSize])
+       w.buf.SetWriterIndex(w.base + w.fixedSize)
+}
+
+// Size returns the bytes written for this row so far.
+func (w *RowWriter) Size() int { return w.buf.WriterIndex() - w.base }
+
+// ToBytes returns a view of the row bytes; it stays valid only until the
+// buffer is written to or reset again.
+func (w *RowWriter) ToBytes() []byte {
+       return w.buf.GetByteSlice(w.base, w.buf.WriterIndex())
+}
+
+func (w *RowWriter) slot(i int) int {
+       if uint(i) >= uint(w.numFields) {
+               panic(fmt.Sprintf("row: field index %d out of range [0, %d)", 
i, w.numFields))
+       }
+       return w.base + w.bitmapWidth + i*8
+}
+
+// SetNullAt marks field i null and zeroes its slot.
+func (w *RowWriter) SetNullAt(i int) {
+       slot := w.slot(i)
+       data := w.buf.GetData()
+       setBit(data[w.base:w.base+w.bitmapWidth], i)
+       binary.LittleEndian.PutUint64(data[slot:], 0)
+}
+
+func (w *RowWriter) SetNotNullAt(i int) {
+       w.slot(i) // bounds check
+       clearBit(w.buf.GetData()[w.base:w.base+w.bitmapWidth], i)
+}
+
+func (w *RowWriter) WriteBool(i int, v bool) {
+       slot := w.slot(i)
+       if v {
+               w.buf.GetData()[slot] = 1
+       } else {
+               w.buf.GetData()[slot] = 0
+       }
+}
+
+func (w *RowWriter) WriteInt8(i int, v int8) {
+       w.buf.GetData()[w.slot(i)] = byte(v)
+}
+
+func (w *RowWriter) WriteInt16(i int, v int16) {
+       binary.LittleEndian.PutUint16(w.buf.GetData()[w.slot(i):], uint16(v))
+}
+
+func (w *RowWriter) WriteInt32(i int, v int32) {
+       binary.LittleEndian.PutUint32(w.buf.GetData()[w.slot(i):], uint32(v))
+}
+
+func (w *RowWriter) WriteInt64(i int, v int64) {
+       binary.LittleEndian.PutUint64(w.buf.GetData()[w.slot(i):], uint64(v))
+}
+
+func (w *RowWriter) WriteFloat32(i int, v float32) {
+       binary.LittleEndian.PutUint32(w.buf.GetData()[w.slot(i):], 
math.Float32bits(v))
+}
+
+func (w *RowWriter) WriteFloat64(i int, v float64) {
+       binary.LittleEndian.PutUint64(w.buf.GetData()[w.slot(i):], 
math.Float64bits(v))
+}
+
+func (w *RowWriter) WriteDate(i int, d fory.Date) error {
+       days, err := fory.DateToEpochDay(d)
+       if err != nil {
+               return err
+       }
+       if days < math.MinInt32 || days > math.MaxInt32 {
+               return fmt.Errorf("row: date %v out of date32 range", d)
+       }
+       w.WriteInt32(i, int32(days))
+       return nil
+}
+
+func (w *RowWriter) WriteTimestamp(i int, t time.Time) {
+       w.WriteInt64(i, t.UnixMicro())
+}
+
+func (w *RowWriter) WriteDuration(i int, d time.Duration) {
+       w.WriteInt64(i, d.Microseconds())
+}
+
+func (w *RowWriter) WriteString(i int, s string) error {
+       start := appendStringRegion(w.buf, s)
+       return w.SetOffsetAndSize(i, start, len(s))
+}
+
+func (w *RowWriter) WriteBytes(i int, b []byte) error {
+       start := appendBytesRegion(w.buf, b)
+       return w.SetOffsetAndSize(i, start, len(b))
+}
+
+// SetOffsetAndSize patches field i's slot with the row-relative offset
+// and byte size of a value already appended to the variable data region.
+// Use it after writing a nested struct, array, or map at absStart.
+// Offsets and sizes beyond 32 bits are rejected: the wire format packs
+// both into one slot, and truncating would corrupt the row silently.
+func (w *RowWriter) SetOffsetAndSize(i, absStart, size int) error {
+       rel := absStart - w.base
+       if uint64(rel) > math.MaxUint32 || uint64(size) > math.MaxUint32 {
+               return fmt.Errorf("row: value at offset %d with %d bytes 
exceeds the 32-bit wire format limit", rel, size)
+       }
+       binary.LittleEndian.PutUint64(w.buf.GetData()[w.slot(i):], 
uint64(rel)<<32|uint64(size))
+       return nil
+}
+
+// ArrayWriter writes one array: an 8-byte element count, a null bitmap,
+// then elements at their natural width (variable-width elements use
+// 8-byte offset+size slots). Offsets are relative to the array base.
+type ArrayWriter struct {
+       elem        Field
+       buf         *fory.ByteBuffer
+       base        int
+       elemSize    int
+       numElements int
+       headerBytes int
+}
+
+func NewArrayWriter(elem Field, buf *fory.ByteBuffer) *ArrayWriter {
+       elemSize := elem.Type.ByteWidth()
+       if elemSize < 0 {
+               elemSize = 8
+       }
+       return &ArrayWriter{elem: elem, buf: buf, elemSize: elemSize}
+}
+
+func (w *ArrayWriter) Buffer() *fory.ByteBuffer { return w.buf }
+
+// Reset rebases the writer at the current writer index and writes the
+// array header plus a zeroed element region for numElements elements.
+func (w *ArrayWriter) Reset(numElements int) error {
+       if numElements < 0 {
+               return fmt.Errorf("row: negative array length %d", numElements)
+       }
+       dataBytes := int64(numElements) * int64(w.elemSize)
+       if dataBytes > maxArrayDataBytes {
+               return fmt.Errorf("row: array of %d elements exceeds maximum 
size", numElements)
+       }

Review Comment:
   **[Suggestion]** The int64 multiplication `int64(numElements) * 
int64(w.elemSize)` overflows for extreme `numElements`, wrapping `dataBytes` 
negative and bypassing the `> maxArrayDataBytes` guard. The trigger is 
physically unallocatable, but the explicit guard is provably defeated. — 
Failure scenario: `numElements > MaxInt64/8` wraps `dataBytes` negative, 
producing an obscure runtime panic instead of the intended clean error.
   
   ```suggestion
        if int64(numElements) > maxArrayDataBytes/int64(w.elemSize) {
                return fmt.Errorf("row: array of %d elements exceeds maximum 
size", numElements)
        }
        dataBytes := int64(numElements) * int64(w.elemSize)
   ```
   
   _— Qwen3-235B-A22B via Qwen Code /review_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to