writeHeader prepares and writes collection metadata including: - Collection size - Type consistency flags - Element type information (if homogeneous) Returns pointer to TypeInfo to avoid copy overhead.
(ctx *WriteContext, buf *ByteBuffer, value reflect.Value)
| 104 | // - Element type information (if homogeneous) |
| 105 | // Returns pointer to TypeInfo to avoid copy overhead. |
| 106 | func (s sliceDynSerializer) writeHeader(ctx *WriteContext, buf *ByteBuffer, value reflect.Value) (byte, *TypeInfo) { |
| 107 | collectFlag := CollectionDefaultFlag |
| 108 | var elemTypeInfo *TypeInfo |
| 109 | hasNull := false |
| 110 | hasSameType := true |
| 111 | |
| 112 | // Iterate through elements to check for nulls and type consistency |
| 113 | var firstType reflect.Type |
| 114 | var firstElem reflect.Value |
| 115 | for i := 0; i < value.Len(); i++ { |
| 116 | elem := value.Index(i).Elem() |
| 117 | if isNull(elem) { |
| 118 | hasNull = true |
| 119 | continue |
| 120 | } |
| 121 | |
| 122 | // Track first non-null element type |
| 123 | if firstType == nil { |
| 124 | firstType = elem.Type() |
| 125 | firstElem = elem |
| 126 | } else { |
| 127 | // Compare each element's type with the first element's type |
| 128 | if firstType != elem.Type() { |
| 129 | hasSameType = false |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | // Only get elemTypeInfo if all elements have same type |
| 134 | if hasSameType && firstElem.IsValid() { |
| 135 | elemTypeInfo, _ = ctx.TypeResolver().getTypeInfo(firstElem, true) |
| 136 | } |
| 137 | |
| 138 | // Set collection flags based on findings |
| 139 | if hasNull { |
| 140 | collectFlag |= CollectionHasNull // Mark if collection contains null values |
| 141 | } |
| 142 | if hasSameType { |
| 143 | collectFlag |= CollectionIsSameType // Mark if elements have same types |
| 144 | } |
| 145 | |
| 146 | // Enable reference tracking if configured and element type supports it |
| 147 | if ctx.TrackRef() && (elemTypeInfo == nil || elemTypeInfo.NeedWriteRef) { |
| 148 | collectFlag |= CollectionTrackingRef |
| 149 | } |
| 150 | |
| 151 | // WriteData metadata to buffer |
| 152 | buf.WriteVarUint32(uint32(value.Len())) // Collection size |
| 153 | buf.WriteInt8(int8(collectFlag)) // Collection flags |
| 154 | |
| 155 | // WriteData element type info if all elements have same type and not using declared type |
| 156 | if hasSameType && (collectFlag&CollectionIsDeclElementType == 0) && elemTypeInfo != nil { |
| 157 | ctx.TypeResolver().WriteTypeInfo(buf, elemTypeInfo, ctx.Err()) |
| 158 | } |
| 159 | |
| 160 | return byte(collectFlag), elemTypeInfo |
| 161 | } |
| 162 | |
| 163 | // writeSameType efficiently serializes a slice where all elements share the same type |
no test coverage detected