Optimization to avoid allocation of heap allocations/temporary strings via formatValue when dealing with primitive types. It returns (handled, error). When handled is false, the caller should fall back to formatValue.
(w io.Writer, v interface{})
| 129 | // Optimization to avoid allocation of heap allocations/temporary strings via formatValue when dealing with primitive types. |
| 130 | // It returns (handled, error). When handled is false, the caller should fall back to formatValue. |
| 131 | func writeValueFast(w io.Writer, v interface{}) (bool, error) { |
| 132 | switch x := v.(type) { |
| 133 | case string: |
| 134 | _, err := w.Write([]byte(quote(x))) |
| 135 | return true, err |
| 136 | case bool: |
| 137 | if x { |
| 138 | _, err := w.Write([]byte("true")) |
| 139 | return true, err |
| 140 | } |
| 141 | _, err := w.Write([]byte("false")) |
| 142 | return true, err |
| 143 | |
| 144 | // signed ints |
| 145 | case int: |
| 146 | return writeSignedInt(w, int64(x)) |
| 147 | case int8: |
| 148 | return writeSignedInt(w, int64(x)) |
| 149 | case int16: |
| 150 | return writeSignedInt(w, int64(x)) |
| 151 | case int32: |
| 152 | return writeSignedInt(w, int64(x)) |
| 153 | case int64: |
| 154 | return writeSignedInt(w, x) |
| 155 | |
| 156 | // unsigned ints |
| 157 | case uint: |
| 158 | return writeUnsignedInt(w, uint64(x)) |
| 159 | case uint8: |
| 160 | return writeUnsignedInt(w, uint64(x)) |
| 161 | case uint16: |
| 162 | return writeUnsignedInt(w, uint64(x)) |
| 163 | case uint32: |
| 164 | return writeUnsignedInt(w, uint64(x)) |
| 165 | case uint64: |
| 166 | return writeUnsignedInt(w, x) |
| 167 | |
| 168 | // floats: prefer 'g' to keep output bounded (matches fmt default) |
| 169 | case float32: |
| 170 | var a [32]byte |
| 171 | _, err := w.Write(strconv.AppendFloat(a[:0], float64(x), 'g', -1, 32)) |
| 172 | return true, err |
| 173 | case float64: |
| 174 | var a [32]byte |
| 175 | _, err := w.Write(strconv.AppendFloat(a[:0], x, 'g', -1, 64)) |
| 176 | return true, err |
| 177 | default: |
| 178 | return false, nil |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | type Formatter struct { |
| 183 | ErrorCallback func(slog.Field, error) |
no test coverage detected