File: hit.go

package info (click to toggle)
golang-github-meilisearch-meilisearch-go 0.34.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,084 kB
  • sloc: makefile: 9
file content (415 lines) | stat: -rw-r--r-- 11,327 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package meilisearch

import (
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"sync"
)

type (
	Hit  map[string]json.RawMessage // Hit is a map of key and value raw buffer
	Hits []Hit                      // Hits is an alias for a slice of Hit.
)

// Deprecated: Decode decodes a single Hit into the provided struct.
//
// Please use DecodeInto for better performance without intermediate marshaling.
func (h Hit) Decode(vPtr interface{}) error {
	if vPtr == nil || reflect.ValueOf(vPtr).Kind() != reflect.Ptr {
		return errors.New("vPtr must be a non-nil pointer")
	}

	raw, err := json.Marshal(h)
	if err != nil {
		return fmt.Errorf("failed to marshal hit: %w", err)
	}

	return json.Unmarshal(raw, vPtr)
}

// DecodeInto decodes a single Hit into the provided struct without intermediate marshaling.
func (h Hit) DecodeInto(out any) error {
	if out == nil {
		return errors.New("out must be a non-nil pointer")
	}
	rv := reflect.ValueOf(out)
	if rv.Kind() != reflect.Ptr || rv.IsNil() {
		return errors.New("out must be a non-nil pointer")
	}
	rv = rv.Elem()

	switch rv.Kind() {
	case reflect.Struct:
		// existing struct path (keep your current implementation) ...
		ti := getTypeInfo(rv.Type())
		for key, raw := range h {
			if len(raw) == 0 {
				continue
			}
			idx, ok := ti.byNameIndex[key]
			if !ok {
				continue
			}
			f := ti.fields[idx]
			fv, ok := fieldByIndexPathAlloc(rv, f.indexPath)
			if !ok {
				continue
			}
			if isJSONNull(raw) {
				if fv.CanSet() {
					fv.Set(reflect.Zero(fv.Type()))
				}
				continue
			}
			if f.hasString {
				if err := unmarshalSingleField(rv.Addr().Interface(), f.jsonName, raw); err != nil {
					return fmt.Errorf("decode field %q: %w", key, err)
				}
				continue
			}
			if !fv.CanAddr() {
				continue
			}
			if err := json.Unmarshal(raw, fv.Addr().Interface()); err != nil {
				return fmt.Errorf("decode field %q: %w", key, err)
			}
		}
		return nil

	case reflect.Map:
		// NEW: map[string]T support
		if rv.Type().Key().Kind() != reflect.String {
			return fmt.Errorf("map key must be string, got %s", rv.Type().Key())
		}
		if rv.IsNil() {
			rv.Set(reflect.MakeMapWithSize(rv.Type(), len(h)))
		}
		elemT := rv.Type().Elem()
		for k, raw := range h {
			// For null values, set zero (nil for pointer/slice/map/interface, 0 for numbers/bool)
			if isJSONNull(raw) {
				rv.SetMapIndex(reflect.ValueOf(k), reflect.Zero(elemT))
				continue
			}
			elemV := reflect.New(elemT) // *elemT
			// If elemT is interface{}, this is *interface{} and is fine.
			if err := json.Unmarshal(raw, elemV.Interface()); err != nil {
				return fmt.Errorf("decode map value for key %q: %w", k, err)
			}
			// Store the concrete elem (dereference)
			rv.SetMapIndex(reflect.ValueOf(k), elemV.Elem())
		}
		return nil

	default:
		return fmt.Errorf("out must point to a struct or map, got %T", out)
	}
}

// DecodeWith decodes a Hit into the provided struct using the provided marshal and unmarshal functions.
func (h Hit) DecodeWith(vPtr interface{}, marshal JSONMarshal, unmarshal JSONUnmarshal) error {
	if vPtr == nil || reflect.ValueOf(vPtr).Kind() != reflect.Ptr {
		return errors.New("vPtr must be a non-nil pointer")
	}

	raw, err := marshal(h)
	if err != nil {
		return fmt.Errorf("failed to marshal hit: %w", err)
	}

	return unmarshal(raw, vPtr)
}

func (h Hits) Len() int {
	return len(h)
}

// Deprecated: Decode decodes the Hits into the provided target slice.
//
// Please use DecodeInto for better performance without intermediate marshaling.
func (h Hits) Decode(vSlicePtr interface{}) error {
	v := reflect.ValueOf(vSlicePtr)

	if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
		return fmt.Errorf("v must be a pointer to a slice, got %T", vSlicePtr)
	}

	raw := []Hit(h)
	buf, err := json.Marshal(raw)
	if err != nil {
		return fmt.Errorf("failed to marshal hits: %w", err)
	}

	return json.Unmarshal(buf, vSlicePtr)
}

// DecodeWith decodes a Hits into the provided struct using the provided marshal and unmarshal functions.
func (h Hits) DecodeWith(vSlicePtr interface{}, marshal JSONMarshal, unmarshal JSONUnmarshal) error {
	v := reflect.ValueOf(vSlicePtr)

	if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
		return errors.New("v must be a pointer to a slice")
	}

	raw := []Hit(h)
	buf, err := marshal(raw)
	if err != nil {
		return fmt.Errorf("failed to marshal hit: %w", err)
	}

	return unmarshal(buf, vSlicePtr)
}

// DecodeInto decodes hs into the provided slice pointer without re-marshal.
// vSlicePtr must be a non-nil pointer to a slice whose element type is a struct or *struct.
// Example:
//
//	var out []exampleBookForTest
//	if err := hits.DecodeInto(&out); err != nil { ... }
//
//	var outPtr []*exampleBookForTest
//	if err := hits.DecodeInto(&outPtr); err != nil { ... }
func (h Hits) DecodeInto(vSlicePtr interface{}) error {
	if vSlicePtr == nil {
		return fmt.Errorf("vSlicePtr must be a non-nil pointer to a slice")
	}
	rv := reflect.ValueOf(vSlicePtr)
	if rv.Kind() != reflect.Ptr || rv.IsNil() {
		return fmt.Errorf("vSlicePtr must be a non-nil pointer, got %T", vSlicePtr)
	}
	sv := rv.Elem()
	if sv.Kind() != reflect.Slice {
		return fmt.Errorf("vSlicePtr must point to a slice, got %s", sv.Kind())
	}

	elemType := sv.Type().Elem()
	out := reflect.MakeSlice(sv.Type(), 0, len(h))

	switch elemType.Kind() {
	case reflect.Struct:
		for i := range h {
			elemPtr := reflect.New(elemType)
			if err := h[i].DecodeInto(elemPtr.Interface()); err != nil {
				return fmt.Errorf("decode hits[%d]: %w", i, err)
			}
			out = reflect.Append(out, elemPtr.Elem())
		}

	case reflect.Ptr:
		et := elemType.Elem()
		switch et.Kind() {
		case reflect.Struct:
			for i := range h {
				elemPtr := reflect.New(et)
				if err := h[i].DecodeInto(elemPtr.Interface()); err != nil {
					return fmt.Errorf("decode hits[%d]: %w", i, err)
				}
				out = reflect.Append(out, elemPtr.Convert(elemType))
			}
		case reflect.Map:
			// *** FIX 1: use et (map type), not elemType (pointer type)
			if et.Key().Kind() != reflect.String {
				return fmt.Errorf("slice element must be map with string key, got %s", et)
			}
			for i := range h {
				// allocate *map[string]V and initialize the map
				mPtr := reflect.New(et)              // *map[string]V
				mPtr.Elem().Set(reflect.MakeMap(et)) // init
				// decode into *map
				if err := h[i].DecodeInto(mPtr.Interface()); err != nil {
					return fmt.Errorf("decode hits[%d]: %w", i, err)
				}
				// append the pointer as required by [] *map[string]V
				out = reflect.Append(out, mPtr.Convert(elemType))
			}
		default:
			return fmt.Errorf("slice element must be struct, *struct, or *map[string]T, got %s", elemType)
		}

	case reflect.Map:
		if elemType.Key().Kind() != reflect.String {
			return fmt.Errorf("slice element must be map with string key, got %s", elemType)
		}
		for i := range h {
			// allocate *map[string]V and initialize
			mPtr := reflect.New(elemType)              // *map[string]V
			mPtr.Elem().Set(reflect.MakeMap(elemType)) // init
			// decode into *map
			if err := h[i].DecodeInto(mPtr.Interface()); err != nil {
				return fmt.Errorf("decode hits[%d]: %w", i, err)
			}
			// append the map value (dereferenced)
			out = reflect.Append(out, mPtr.Elem())
		}

	default:
		return fmt.Errorf("slice element must be struct, *struct, map[string]T, or *map[string]T, got %s", elemType)
	}

	sv.Set(out)
	return nil
}

type fieldMeta struct {
	jsonName  string
	indexPath []int
	hasString bool
}

type typeInfo struct {
	fields      []fieldMeta
	byNameIndex map[string]int // json name -> index in fields
}

var (
	typeInfoCache sync.Map // reflect.Type -> *typeInfo
)

func getTypeInfo(t reflect.Type) *typeInfo {
	if v, ok := typeInfoCache.Load(t); ok {
		return v.(*typeInfo)
	}
	f := collectFields(t, nil)
	ti := &typeInfo{
		fields:      f,
		byNameIndex: make(map[string]int, len(f)),
	}
	for i := range f {
		ti.byNameIndex[f[i].jsonName] = i
	}
	typeInfoCache.Store(t, ti)
	return ti
}

func collectFields(t reflect.Type, prefix []int) []fieldMeta {
	var out []fieldMeta

	// Walk struct fields, including anonymous/embedded.
	for i := 0; i < t.NumField(); i++ {
		sf := t.Field(i)
		// Skip unexported (PkgPath != "", except for embedded anonymous exported types)
		if sf.PkgPath != "" && !sf.Anonymous {
			continue
		}
		tag := sf.Tag.Get("json")
		if tag == "-" {
			continue
		}
		name := sf.Name
		hasString := false
		if tag != "" {
			// split first token (name) and options
			if c := indexByte(tag, ','); c >= 0 {
				nameToken := tag[:c]
				if nameToken != "" {
					name = nameToken
				}
				if hasJSONTagOption(tag[c+1:], "string") {
					hasString = true
				}
			} else {
				// tag without options
				name = tag
			}
		}
		idx := append(append([]int(nil), prefix...), i)

		// Inline embedded struct or *struct (pointer-embedded) when not renamed.
		if sf.Anonymous && name == sf.Name {
			u := sf.Type
			if u.Kind() == reflect.Ptr {
				u = u.Elem()
			}
			if u.Kind() == reflect.Struct {
				out = append(out, collectFields(u, idx)...)
				continue
			}
		}

		out = append(out, fieldMeta{
			jsonName:  name,
			indexPath: idx,
			hasString: hasString,
		})
	}
	return out
}

// small helper: faster than strings.IndexByte here, avoids import
func indexByte(s string, c byte) int {
	for i := 0; i < len(s); i++ {
		if s[i] == c {
			return i
		}
	}
	return -1
}

// hasJSONTagOption reports whether the comma-separated tag options contain opt.
func hasJSONTagOption(opts, opt string) bool {
	// opts like: "omitempty,string"
	start := 0
	for i := 0; i <= len(opts); i++ {
		if i == len(opts) || opts[i] == ',' {
			if opts[start:i] == opt {
				return true
			}
			start = i + 1
		}
	}
	return false
}

// fieldByIndexPathAlloc walks from the addressable struct value rv to the field
// indicated by indexPath, allocating intermediate *struct fields if needed.
// Returns the leaf field value and whether it is usable (addressable/settable).
func fieldByIndexPathAlloc(rv reflect.Value, indexPath []int) (reflect.Value, bool) {
	cur := rv
	for _, idx := range indexPath {
		if cur.Kind() == reflect.Ptr {
			if cur.IsNil() {
				if !cur.CanSet() {
					return reflect.Value{}, false
				}
				if cur.Type().Elem().Kind() != reflect.Struct {
					return reflect.Value{}, false
				}
				cur.Set(reflect.New(cur.Type().Elem()))
			}
			cur = cur.Elem()
		}
		if cur.Kind() != reflect.Struct {
			return reflect.Value{}, false
		}

		if idx < 0 || idx >= cur.NumField() {
			return reflect.Value{}, false
		}

		cur = cur.Field(idx)
	}
	if cur.Kind() == reflect.Ptr && cur.IsNil() {
		if cur.CanSet() && cur.Type().Elem().Kind() == reflect.Struct {
			cur.Set(reflect.New(cur.Type().Elem()))
		}
	}
	return cur, cur.CanAddr() || cur.CanSet()
}

// unmarshalSingleField unmarshals a single field into dst (pointer to struct)
// by constructing a minimal {"name": raw} object and delegating to encoding/json.
// This preserves stdlib behaviors such as json:",string".
func unmarshalSingleField(dst any, name string, raw []byte) error {
	tmp := map[string]json.RawMessage{name: json.RawMessage(raw)}
	b, err := json.Marshal(tmp)
	if err != nil {
		return err
	}
	return json.Unmarshal(b, dst)
}

func isJSONNull(b []byte) bool {
	return len(b) == 4 && b[0] == 'n' && b[1] == 'u' && b[2] == 'l' && b[3] == 'l'
}