cuelang.org/go@v0.13.0/cue/decode.go (about)

     1  // Copyright 2021 CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cue
    16  
    17  import (
    18  	"bytes"
    19  	"cmp"
    20  	"encoding"
    21  	"encoding/json"
    22  	"reflect"
    23  	"slices"
    24  	"strconv"
    25  	"strings"
    26  	"sync"
    27  	"unicode"
    28  	"unicode/utf8"
    29  
    30  	"cuelang.org/go/cue/errors"
    31  	"cuelang.org/go/internal/core/adt"
    32  )
    33  
    34  // Decode initializes the value pointed to by x with Value v.
    35  // An error is returned if x is nil or not a pointer.
    36  //
    37  // If x is a struct, Decode will validate the constraints specified in the field tags.
    38  //
    39  // If x contains a [Value], that part of x will be set to the value
    40  // at the corresponding part of v. This allows decoding values
    41  // that aren't entirely concrete into a Go type.
    42  func (v Value) Decode(x interface{}) error {
    43  	var d decoder
    44  	w := reflect.ValueOf(x)
    45  	if w.Kind() != reflect.Pointer || w.IsNil() {
    46  		d.addErr(errors.Newf(v.Pos(), "cannot decode into unsettable value"))
    47  		return d.errs
    48  	}
    49  	d.decode(w.Elem(), v, false)
    50  	return d.errs
    51  }
    52  
    53  type decoder struct {
    54  	errs errors.Error
    55  }
    56  
    57  func (d *decoder) addErr(err error) {
    58  	if err != nil {
    59  		d.errs = errors.Append(d.errs, errors.Promote(err, ""))
    60  	}
    61  }
    62  
    63  func incompleteError(v Value) errors.Error {
    64  	return &valueError{
    65  		v: v,
    66  		err: &adt.Bottom{
    67  			Code: adt.IncompleteError,
    68  			Err: errors.Newf(v.Pos(),
    69  				"cannot convert non-concrete value %v", v)},
    70  	}
    71  }
    72  
    73  func (d *decoder) clear(x reflect.Value) {
    74  	if x.CanSet() {
    75  		x.SetZero()
    76  	}
    77  }
    78  
    79  var valueType = reflect.TypeFor[Value]()
    80  
    81  func (d *decoder) decode(x reflect.Value, v Value, isPtr bool) {
    82  	if !x.IsValid() {
    83  		d.addErr(errors.Newf(v.Pos(), "cannot decode into invalid value"))
    84  		return
    85  	}
    86  
    87  	v, _ = v.Default()
    88  	if v.v == nil {
    89  		d.clear(x)
    90  		return
    91  	}
    92  
    93  	if err := v.Err(); err != nil {
    94  		d.addErr(err)
    95  		return
    96  	}
    97  	if x.Type() == valueType {
    98  		x.Set(reflect.ValueOf(v))
    99  		return
   100  	}
   101  
   102  	switch x.Kind() {
   103  	case reflect.Pointer, reflect.Map, reflect.Slice, reflect.Interface:
   104  		// nullable types
   105  		if v.IsNull() || !v.IsConcrete() {
   106  			d.clear(x)
   107  			return
   108  		}
   109  
   110  	default:
   111  		// TODO: allow incomplete values.
   112  		if !v.IsConcrete() {
   113  			d.addErr(incompleteError(v))
   114  			return
   115  		}
   116  	}
   117  
   118  	ij, it, x := indirect(x, v.IsNull())
   119  
   120  	if ij != nil {
   121  		b, err := v.MarshalJSON()
   122  		d.addErr(err)
   123  		d.addErr(ij.UnmarshalJSON(b))
   124  		return
   125  	}
   126  
   127  	if it != nil {
   128  		b, err := v.Bytes()
   129  		if err != nil {
   130  			err = errors.Wrapf(err, v.Pos(), "Decode")
   131  			d.addErr(err)
   132  			return
   133  		}
   134  		d.addErr(it.UnmarshalText(b))
   135  		return
   136  	}
   137  
   138  	kind := x.Kind()
   139  
   140  	if kind == reflect.Interface {
   141  		value := d.interfaceValue(v)
   142  		x.Set(reflect.ValueOf(value))
   143  		return
   144  	}
   145  
   146  	switch kind {
   147  	case reflect.Pointer:
   148  		d.decode(x.Elem(), v, true)
   149  
   150  	case reflect.Bool:
   151  		b, err := v.Bool()
   152  		d.addErr(err)
   153  		x.SetBool(b)
   154  
   155  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   156  		i, err := v.Int64()
   157  		d.addErr(err)
   158  		if x.OverflowInt(i) {
   159  			d.addErr(errors.Newf(v.Pos(), "integer %d overflows %s", i, kind))
   160  			break
   161  		}
   162  		x.SetInt(i)
   163  
   164  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
   165  		i, err := v.Uint64()
   166  		d.addErr(err)
   167  		if x.OverflowUint(i) {
   168  			d.addErr(errors.Newf(v.Pos(), "integer %d overflows %s", i, kind))
   169  			break
   170  		}
   171  		x.SetUint(i)
   172  
   173  	case reflect.Float32, reflect.Float64:
   174  		f, err := v.Float64()
   175  		d.addErr(err)
   176  		if x.OverflowFloat(f) {
   177  			d.addErr(errors.Newf(v.Pos(), "float %g overflows %s", f, kind))
   178  			break
   179  		}
   180  		x.SetFloat(f)
   181  
   182  	case reflect.String:
   183  		s, err := v.String()
   184  		d.addErr(err)
   185  		x.SetString(s)
   186  
   187  	case reflect.Array:
   188  		d.clear(x)
   189  
   190  		t := x.Type()
   191  		n := x.Len()
   192  
   193  		if t.Elem().Kind() == reflect.Uint8 && v.Kind() == BytesKind {
   194  			b, err := v.Bytes()
   195  			d.addErr(err)
   196  			for i, c := range b {
   197  				if i >= n {
   198  					break
   199  				}
   200  				x.Index(i).SetUint(uint64(c))
   201  			}
   202  			break
   203  		}
   204  
   205  		var a []Value
   206  		list, err := v.List()
   207  		d.addErr(err)
   208  		for list.Next() {
   209  			a = append(a, list.Value())
   210  		}
   211  
   212  		for i, v := range a {
   213  			if i >= n {
   214  				break
   215  			}
   216  			d.decode(x.Index(i), v, false)
   217  		}
   218  
   219  	case reflect.Slice:
   220  		t := x.Type()
   221  		if t.Elem().Kind() == reflect.Uint8 && v.Kind() == BytesKind {
   222  			b, err := v.Bytes()
   223  			d.addErr(err)
   224  			x.SetBytes(b)
   225  			break
   226  		}
   227  
   228  		var a []Value
   229  		list, err := v.List()
   230  		d.addErr(err)
   231  		for list.Next() {
   232  			a = append(a, list.Value())
   233  		}
   234  
   235  		switch cap := x.Cap(); {
   236  		case cap == 0, // force a non-nil list
   237  			cap < len(a):
   238  			x.Set(reflect.MakeSlice(t, len(a), len(a)))
   239  
   240  		default:
   241  			x.SetLen(len(a))
   242  		}
   243  
   244  		for i, v := range a {
   245  			d.decode(x.Index(i), v, false)
   246  		}
   247  
   248  	case reflect.Struct:
   249  		d.convertStruct(x, v)
   250  
   251  	case reflect.Map:
   252  		d.convertMap(x, v)
   253  
   254  	default:
   255  		d.clear(x)
   256  	}
   257  }
   258  
   259  func (d *decoder) interfaceValue(v Value) (x interface{}) {
   260  	var err error
   261  	v, _ = v.Default()
   262  	switch v.Kind() {
   263  	case NullKind:
   264  		return nil
   265  
   266  	case BoolKind:
   267  		x, err = v.Bool()
   268  
   269  	case IntKind:
   270  		if i, err := v.Int64(); err == nil {
   271  			return i
   272  		}
   273  		x, err = v.Int(nil)
   274  
   275  	case FloatKind:
   276  		x, err = v.Float64() // or big int or
   277  
   278  	case StringKind:
   279  		x, err = v.String()
   280  
   281  	case BytesKind:
   282  		x, err = v.Bytes()
   283  
   284  	case ListKind:
   285  		var a []interface{}
   286  		list, err := v.List()
   287  		d.addErr(err)
   288  		for list.Next() {
   289  			a = append(a, d.interfaceValue(list.Value()))
   290  		}
   291  		if a == nil {
   292  			a = []interface{}{}
   293  		}
   294  		x = a
   295  
   296  	case StructKind:
   297  		m := map[string]interface{}{}
   298  		iter, err := v.Fields()
   299  		d.addErr(err)
   300  		for iter.Next() {
   301  			m[iter.Selector().Unquoted()] = d.interfaceValue(iter.Value())
   302  		}
   303  		x = m
   304  
   305  	default:
   306  		err = incompleteError(v)
   307  	}
   308  
   309  	d.addErr(err)
   310  	return x
   311  }
   312  
   313  var textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
   314  
   315  // convertMap keeps an existing map and overwrites any entry found in v,
   316  // keeping other preexisting entries.
   317  func (d *decoder) convertMap(x reflect.Value, v Value) {
   318  	// Delete existing elements
   319  	t := x.Type()
   320  
   321  	// Map key must either have string kind, have an integer kind,
   322  	// or be an encoding.TextUnmarshaler.
   323  	switch t.Key().Kind() {
   324  	case reflect.String,
   325  		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   326  		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   327  	default:
   328  		if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) {
   329  			d.addErr(errors.Newf(v.Pos(), "unsupported key type %v", t.Key()))
   330  			return
   331  		}
   332  	}
   333  
   334  	if x.IsNil() {
   335  		x.Set(reflect.MakeMap(t))
   336  	}
   337  
   338  	var mapElem reflect.Value
   339  
   340  	iter, err := v.Fields()
   341  	d.addErr(err)
   342  	for iter.Next() {
   343  		key := iter.Selector().Unquoted()
   344  
   345  		var kv reflect.Value
   346  		kt := t.Key()
   347  		if reflect.PointerTo(kt).Implements(textUnmarshalerType) {
   348  			kv = reflect.New(kt)
   349  			err := kv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(key))
   350  			d.addErr(err)
   351  			kv = kv.Elem()
   352  		} else {
   353  			switch kt.Kind() {
   354  			case reflect.String:
   355  				kv = reflect.ValueOf(key).Convert(kt)
   356  			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   357  				n, err := strconv.ParseInt(key, 10, 64)
   358  				d.addErr(err)
   359  				if kt.OverflowInt(n) {
   360  					d.addErr(errors.Newf(v.Pos(), "key integer %d overflows %s", n, kt))
   361  					break
   362  				}
   363  				kv = reflect.ValueOf(n).Convert(kt)
   364  
   365  			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   366  				n, err := strconv.ParseUint(key, 10, 64)
   367  				d.addErr(err)
   368  				if kt.OverflowUint(n) {
   369  					d.addErr(errors.Newf(v.Pos(), "key integer %d overflows %s", n, kt))
   370  					break
   371  				}
   372  				kv = reflect.ValueOf(n).Convert(kt)
   373  
   374  			default:
   375  				panic("json: Unexpected key type") // should never occur
   376  			}
   377  		}
   378  
   379  		if !mapElem.IsValid() {
   380  			mapElem = reflect.New(t.Elem()).Elem()
   381  		} else {
   382  			mapElem.SetZero()
   383  		}
   384  		d.decode(mapElem, iter.Value(), false)
   385  
   386  		if kv.IsValid() {
   387  			x.SetMapIndex(kv, mapElem)
   388  		}
   389  	}
   390  }
   391  
   392  func (d *decoder) convertStruct(x reflect.Value, v Value) {
   393  	t := x.Type()
   394  	fields := cachedTypeFields(t)
   395  
   396  	iter, err := v.Fields()
   397  	d.addErr(err)
   398  	for iter.Next() {
   399  		var f *goField
   400  		key := iter.Selector().Unquoted()
   401  		if i, ok := fields.nameIndex[key]; ok {
   402  			// Found an exact name match.
   403  			f = &fields.list[i]
   404  		} else {
   405  			// Fall back to the expensive case-insensitive
   406  			// linear search.
   407  			key := []byte(key)
   408  			for i := range fields.list {
   409  				ff := &fields.list[i]
   410  				if ff.equalFold(ff.nameBytes, key) {
   411  					f = ff
   412  					break
   413  				}
   414  			}
   415  		}
   416  
   417  		if f == nil {
   418  			continue
   419  		}
   420  
   421  		// Figure out field corresponding to key.
   422  		subv := x
   423  		for _, i := range f.index {
   424  			if subv.Kind() == reflect.Pointer {
   425  				if subv.IsNil() {
   426  					// If a struct embeds a pointer to an unexported type,
   427  					// it is not possible to set a newly allocated value
   428  					// since the field is unexported.
   429  					//
   430  					// See https://golang.org/issue/21357
   431  					if !subv.CanSet() {
   432  						d.addErr(errors.Newf(v.Pos(),
   433  							"cannot set embedded pointer to unexported struct: %v",
   434  							subv.Type().Elem()))
   435  						subv = reflect.Value{}
   436  						break
   437  					}
   438  					subv.Set(reflect.New(subv.Type().Elem()))
   439  				}
   440  				subv = subv.Elem()
   441  			}
   442  			subv = subv.Field(i)
   443  		}
   444  
   445  		// TODO: make this an option
   446  		//  else if d.disallowUnknownFields {
   447  		// 	d.saveError(fmt.Errorf("json: unknown field %q", key))
   448  		// }
   449  
   450  		d.decode(subv, iter.Value(), false)
   451  	}
   452  }
   453  
   454  type structFields struct {
   455  	list      []goField
   456  	nameIndex map[string]int
   457  }
   458  
   459  func isValidTag(s string) bool {
   460  	if s == "" {
   461  		return false
   462  	}
   463  	for _, c := range s {
   464  		switch {
   465  		case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
   466  			// Backslash and quote chars are reserved, but
   467  			// otherwise any punctuation chars are allowed
   468  			// in a tag name.
   469  		case !unicode.IsLetter(c) && !unicode.IsDigit(c):
   470  			return false
   471  		}
   472  	}
   473  	return true
   474  }
   475  
   476  // A field represents a single Go field found in a struct.
   477  type goField struct {
   478  	name      string
   479  	nameBytes []byte                 // []byte(name)
   480  	equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
   481  
   482  	tag       bool
   483  	index     []int
   484  	typ       reflect.Type
   485  	omitEmpty bool
   486  }
   487  
   488  func compareFieldByIndex(a, b goField) int {
   489  	for i, x := range a.index {
   490  		if i >= len(b.index) {
   491  			break
   492  		}
   493  		if c := cmp.Compare(x, b.index[i]); c != 0 {
   494  			return c
   495  		}
   496  	}
   497  	return cmp.Compare(len(a.index), len(b.index))
   498  }
   499  
   500  // typeFields returns a list of fields that JSON should recognize for the given type.
   501  // The algorithm is breadth-first search over the set of structs to include - the top struct
   502  // and then any reachable anonymous structs.
   503  func typeFields(t reflect.Type) structFields {
   504  	// Anonymous fields to explore at the current level and the next.
   505  	current := []goField{}
   506  	next := []goField{{typ: t}}
   507  
   508  	// Count of queued names for current level and the next.
   509  	var count, nextCount map[reflect.Type]int
   510  
   511  	// Types already visited at an earlier level.
   512  	visited := map[reflect.Type]bool{}
   513  
   514  	// Fields found.
   515  	var fields []goField
   516  
   517  	for len(next) > 0 {
   518  		current, next = next, current[:0]
   519  		count, nextCount = nextCount, map[reflect.Type]int{}
   520  
   521  		for _, f := range current {
   522  			if visited[f.typ] {
   523  				continue
   524  			}
   525  			visited[f.typ] = true
   526  
   527  			// Scan f.typ for fields to include.
   528  			for i := range f.typ.NumField() {
   529  				sf := f.typ.Field(i)
   530  				isUnexported := sf.PkgPath != ""
   531  				if sf.Anonymous {
   532  					t := sf.Type
   533  					if t.Kind() == reflect.Pointer {
   534  						t = t.Elem()
   535  					}
   536  					if isUnexported && t.Kind() != reflect.Struct {
   537  						// Ignore embedded fields of unexported non-struct types.
   538  						continue
   539  					}
   540  					// Do not ignore embedded fields of unexported struct types
   541  					// since they may have exported fields.
   542  				} else if isUnexported {
   543  					// Ignore unexported non-embedded fields.
   544  					continue
   545  				}
   546  				tag := sf.Tag.Get("json")
   547  				if tag == "-" {
   548  					continue
   549  				}
   550  				name, opts, _ := strings.Cut(tag, ",")
   551  				if !isValidTag(name) {
   552  					name = ""
   553  				}
   554  				index := make([]int, len(f.index)+1)
   555  				copy(index, f.index)
   556  				index[len(f.index)] = i
   557  
   558  				ft := sf.Type
   559  				if ft.Name() == "" && ft.Kind() == reflect.Pointer {
   560  					// Follow pointer.
   561  					ft = ft.Elem()
   562  				}
   563  
   564  				// Record found field and index sequence.
   565  				if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
   566  					tagged := name != ""
   567  					if name == "" {
   568  						name = sf.Name
   569  					}
   570  					field := goField{
   571  						name:      name,
   572  						tag:       tagged,
   573  						index:     index,
   574  						typ:       ft,
   575  						omitEmpty: tagOptions(opts).Contains("omitempty"),
   576  					}
   577  					field.nameBytes = []byte(field.name)
   578  					field.equalFold = foldFunc(field.nameBytes)
   579  
   580  					fields = append(fields, field)
   581  					if count[f.typ] > 1 {
   582  						// If there were multiple instances, add a second,
   583  						// so that the annihilation code will see a duplicate.
   584  						// It only cares about the distinction between 1 or 2,
   585  						// so don't bother generating any more copies.
   586  						fields = append(fields, fields[len(fields)-1])
   587  					}
   588  					continue
   589  				}
   590  
   591  				// Record new anonymous struct to explore in next round.
   592  				nextCount[ft]++
   593  				if nextCount[ft] == 1 {
   594  					next = append(next, goField{name: ft.Name(), index: index, typ: ft})
   595  				}
   596  			}
   597  		}
   598  	}
   599  
   600  	slices.SortFunc(fields, func(a, b goField) int {
   601  		// sort field by name, breaking ties with depth, then
   602  		// breaking ties with "name came from json tag", then
   603  		// breaking ties with index sequence.
   604  		if c := cmp.Compare(a.name, b.name); c != 0 {
   605  			return c
   606  		}
   607  		if c := cmp.Compare(len(a.index), len(b.index)); c != 0 {
   608  			return c
   609  		}
   610  		if a.tag != b.tag {
   611  			if a.tag {
   612  				return 1
   613  			} else {
   614  				return -1
   615  			}
   616  		}
   617  		return compareFieldByIndex(a, b)
   618  	})
   619  
   620  	// Delete all fields that are hidden by the Go rules for embedded fields,
   621  	// except that fields with JSON tags are promoted.
   622  
   623  	// The fields are sorted in primary order of name, secondary order
   624  	// of field index length. Loop over names; for each name, delete
   625  	// hidden fields by choosing the one dominant field that survives.
   626  	out := fields[:0]
   627  	for advance, i := 0, 0; i < len(fields); i += advance {
   628  		// One iteration per name.
   629  		// Find the sequence of fields with the name of this first field.
   630  		fi := fields[i]
   631  		name := fi.name
   632  		for advance = 1; i+advance < len(fields); advance++ {
   633  			fj := fields[i+advance]
   634  			if fj.name != name {
   635  				break
   636  			}
   637  		}
   638  		if advance == 1 { // Only one field with this name
   639  			out = append(out, fi)
   640  			continue
   641  		}
   642  		dominant, ok := dominantField(fields[i : i+advance])
   643  		if ok {
   644  			out = append(out, dominant)
   645  		}
   646  	}
   647  
   648  	fields = out
   649  	slices.SortFunc(fields, compareFieldByIndex)
   650  
   651  	nameIndex := make(map[string]int, len(fields))
   652  	for i, field := range fields {
   653  		nameIndex[field.name] = i
   654  	}
   655  	return structFields{fields, nameIndex}
   656  }
   657  
   658  // dominantField looks through the fields, all of which are known to
   659  // have the same name, to find the single field that dominates the
   660  // others using Go's embedding rules, modified by the presence of
   661  // JSON tags. If there are multiple top-level fields, the boolean
   662  // will be false: This condition is an error in Go and we skip all
   663  // the fields.
   664  func dominantField(fields []goField) (goField, bool) {
   665  	// The fields are sorted in increasing index-length order, then by presence of tag.
   666  	// That means that the first field is the dominant one. We need only check
   667  	// for error cases: two fields at top level, either both tagged or neither tagged.
   668  	if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag {
   669  		return goField{}, false
   670  	}
   671  	return fields[0], true
   672  }
   673  
   674  var fieldCache sync.Map // map[reflect.Type]structFields
   675  
   676  // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
   677  func cachedTypeFields(t reflect.Type) structFields {
   678  	if f, ok := fieldCache.Load(t); ok {
   679  		return f.(structFields)
   680  	}
   681  	f, _ := fieldCache.LoadOrStore(t, typeFields(t))
   682  	return f.(structFields)
   683  }
   684  
   685  // tagOptions is the string following a comma in a struct field's "json"
   686  // tag, or the empty string. It does not include the leading comma.
   687  type tagOptions string
   688  
   689  // Contains reports whether a comma-separated list of options
   690  // contains a particular substr flag. substr must be surrounded by a
   691  // string boundary or commas.
   692  func (o tagOptions) Contains(optionName string) bool {
   693  	if len(o) == 0 {
   694  		return false
   695  	}
   696  	s := string(o)
   697  	for s != "" {
   698  		var next string
   699  		s, next, _ = strings.Cut(s, ",")
   700  		if s == optionName {
   701  			return true
   702  		}
   703  		s = next
   704  	}
   705  	return false
   706  }
   707  
   708  // foldFunc returns one of four different case folding equivalence
   709  // functions, from most general (and slow) to fastest:
   710  //
   711  // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8
   712  // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S')
   713  // 3) asciiEqualFold, no special, but includes non-letters (including _)
   714  // 4) simpleLetterEqualFold, no specials, no non-letters.
   715  //
   716  // The letters S and K are special because they map to 3 runes, not just 2:
   717  //   - S maps to s and to U+017F 'ſ' Latin small letter long s
   718  //   - k maps to K and to U+212A 'K' Kelvin sign
   719  //
   720  // See https://play.golang.org/p/tTxjOc0OGo
   721  //
   722  // The returned function is specialized for matching against s and
   723  // should only be given s. It's not curried for performance reasons.
   724  func foldFunc(s []byte) func(s, t []byte) bool {
   725  	nonLetter := false
   726  	special := false // special letter
   727  	for _, b := range s {
   728  		if b >= utf8.RuneSelf {
   729  			return bytes.EqualFold
   730  		}
   731  		upper := b & caseMask
   732  		if upper < 'A' || upper > 'Z' {
   733  			nonLetter = true
   734  		} else if upper == 'K' || upper == 'S' {
   735  			// See above for why these letters are special.
   736  			special = true
   737  		}
   738  	}
   739  	if special {
   740  		return equalFoldRight
   741  	}
   742  	if nonLetter {
   743  		return asciiEqualFold
   744  	}
   745  	return simpleLetterEqualFold
   746  }
   747  
   748  const (
   749  	caseMask     = ^byte(0x20) // Mask to ignore case in ASCII.
   750  	kelvin       = '\u212a'
   751  	smallLongEss = '\u017f'
   752  )
   753  
   754  // equalFoldRight is a specialization of bytes.EqualFold when s is
   755  // known to be all ASCII (including punctuation), but contains an 's',
   756  // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t.
   757  // See comments on foldFunc.
   758  func equalFoldRight(s, t []byte) bool {
   759  	for _, sb := range s {
   760  		if len(t) == 0 {
   761  			return false
   762  		}
   763  		tb := t[0]
   764  		if tb < utf8.RuneSelf {
   765  			if sb != tb {
   766  				sbUpper := sb & caseMask
   767  				if 'A' <= sbUpper && sbUpper <= 'Z' {
   768  					if sbUpper != tb&caseMask {
   769  						return false
   770  					}
   771  				} else {
   772  					return false
   773  				}
   774  			}
   775  			t = t[1:]
   776  			continue
   777  		}
   778  		// sb is ASCII and t is not. t must be either kelvin
   779  		// sign or long s; sb must be s, S, k, or K.
   780  		tr, size := utf8.DecodeRune(t)
   781  		switch sb {
   782  		case 's', 'S':
   783  			if tr != smallLongEss {
   784  				return false
   785  			}
   786  		case 'k', 'K':
   787  			if tr != kelvin {
   788  				return false
   789  			}
   790  		default:
   791  			return false
   792  		}
   793  		t = t[size:]
   794  
   795  	}
   796  	return len(t) == 0
   797  }
   798  
   799  // asciiEqualFold is a specialization of bytes.EqualFold for use when
   800  // s is all ASCII (but may contain non-letters) and contains no
   801  // special-folding letters.
   802  // See comments on foldFunc.
   803  func asciiEqualFold(s, t []byte) bool {
   804  	if len(s) != len(t) {
   805  		return false
   806  	}
   807  	for i, sb := range s {
   808  		tb := t[i]
   809  		if sb == tb {
   810  			continue
   811  		}
   812  		if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') {
   813  			if sb&caseMask != tb&caseMask {
   814  				return false
   815  			}
   816  		} else {
   817  			return false
   818  		}
   819  	}
   820  	return true
   821  }
   822  
   823  // simpleLetterEqualFold is a specialization of bytes.EqualFold for
   824  // use when s is all ASCII letters (no underscores, etc) and also
   825  // doesn't contain 'k', 'K', 's', or 'S'.
   826  // See comments on foldFunc.
   827  func simpleLetterEqualFold(s, t []byte) bool {
   828  	if len(s) != len(t) {
   829  		return false
   830  	}
   831  	for i, b := range s {
   832  		if b&caseMask != t[i]&caseMask {
   833  			return false
   834  		}
   835  	}
   836  	return true
   837  }
   838  
   839  // indirect walks down v allocating pointers as needed,
   840  // until it gets to a non-pointer.
   841  // If it encounters an Unmarshaler, indirect stops and returns that.
   842  // If decodingNull is true, indirect stops at the first settable pointer so it
   843  // can be set to nil.
   844  func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
   845  	// Issue #24153 indicates that it is generally not a guaranteed property
   846  	// that you may round-trip a reflect.Value by calling Value.Addr().Elem()
   847  	// and expect the value to still be settable for values derived from
   848  	// unexported embedded struct fields.
   849  	//
   850  	// The logic below effectively does this when it first addresses the value
   851  	// (to satisfy possible pointer methods) and continues to dereference
   852  	// subsequent pointers as necessary.
   853  	//
   854  	// After the first round-trip, we set v back to the original value to
   855  	// preserve the original RW flags contained in reflect.Value.
   856  	v0 := v
   857  	haveAddr := false
   858  
   859  	// If v is a named type and is addressable,
   860  	// start with its address, so that if the type has pointer methods,
   861  	// we find them.
   862  	if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() {
   863  		haveAddr = true
   864  		v = v.Addr()
   865  	}
   866  	for {
   867  		// Load value from interface, but only if the result will be
   868  		// usefully addressable.
   869  		if v.Kind() == reflect.Interface && !v.IsNil() {
   870  			e := v.Elem()
   871  			if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) {
   872  				haveAddr = false
   873  				v = e
   874  				continue
   875  			}
   876  		}
   877  
   878  		if v.Kind() != reflect.Pointer {
   879  			break
   880  		}
   881  
   882  		if decodingNull && v.CanSet() {
   883  			break
   884  		}
   885  
   886  		// Prevent infinite loop if v is an interface pointing to its own address:
   887  		//     var v interface{}
   888  		//     v = &v
   889  		if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
   890  			v = v.Elem()
   891  			break
   892  		}
   893  		if v.IsNil() {
   894  			v.Set(reflect.New(v.Type().Elem()))
   895  		}
   896  		if v.Type().NumMethod() > 0 && v.CanInterface() {
   897  			if u, ok := v.Interface().(json.Unmarshaler); ok {
   898  				return u, nil, reflect.Value{}
   899  			}
   900  			if !decodingNull {
   901  				if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
   902  					return nil, u, reflect.Value{}
   903  				}
   904  			}
   905  		}
   906  
   907  		if haveAddr {
   908  			v = v0 // restore original value after round-trip Value.Addr().Elem()
   909  			haveAddr = false
   910  		} else {
   911  			v = v.Elem()
   912  		}
   913  	}
   914  	return nil, nil, v
   915  }