MCPcopy
hub / github.com/yusing/godoxy / ConvertSlice

Function ConvertSlice

internal/serialization/serialization.go:488–538  ·  view source on GitHub ↗

ConvertSlice converts a source slice to a destination slice. - Elements are converted one by one using the Convert function. - Validation is performed on each element if checkValidateTag is true. - The destination slice is initialized with the source length. - On error, the destination slice is tru

(src reflect.Value, dst reflect.Value, checkValidateTag bool)

Source from the content-addressed store, hash-verified

486// - On error, the destination slice is truncated to the number of
487// successfully converted elements.
488func ConvertSlice(src reflect.Value, dst reflect.Value, checkValidateTag bool) error {
489 if dst.Kind() == reflect.Pointer {
490 if dst.IsNil() && !dst.CanSet() {
491 return fmt.Errorf("convert: dst is %w", ErrNilValue)
492 }
493 initPtr(dst)
494 dst = dst.Elem()
495 }
496
497 if !dst.CanSet() {
498 return fmt.Errorf("convert: dst is %w", ErrUnsettable)
499 }
500
501 if src.Kind() != reflect.Slice {
502 return Convert(src, dst, checkValidateTag)
503 }
504
505 srcLen := src.Len()
506 if srcLen == 0 {
507 dst.SetZero()
508 return nil
509 }
510 if dst.Kind() != reflect.Slice {
511 return fmt.Errorf("convert: %w for %s to %s", ErrUnsupportedConversion, dst.Type(), src.Type())
512 }
513
514 var sliceErrs gperr.Builder
515 numValid := 0
516 gi.ReflectInitSlice(dst, srcLen, srcLen)
517 for j := range srcLen {
518 err := Convert(src.Index(j), dst.Index(numValid), checkValidateTag)
519 if err != nil {
520 sliceErrs.AddSubjectf(err, "[%d]", j)
521 continue
522 }
523 numValid++
524 }
525
526 if dst.Type().Implements(reflect.TypeFor[CustomValidator]()) {
527 err := dst.Interface().(CustomValidator).Validate()
528 if err != nil {
529 sliceErrs.Add(err)
530 }
531 }
532
533 if err := sliceErrs.Error(); err != nil {
534 dst.SetLen(numValid) // shrink to number of elements that were successfully converted
535 return err
536 }
537 return nil
538}
539
540// ConvertString converts a string value to the destination reflect.Value.
541// - It handles various types including numeric types, booleans, time.Duration,

Callers 3

ParseMethod · 0.92
ConvertFunction · 0.85
ConvertStringFunction · 0.85

Calls 7

initPtrFunction · 0.85
ConvertFunction · 0.85
TypeMethod · 0.80
ValidateMethod · 0.65
AddMethod · 0.65
LenMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected