elvish/pkg/eval/vals/len.go
Qi Xiao 96752afa4d Make struct maps indistinguishable from maps to Elvish code.
Struct map is a mechanism to let Go code expose simple structs to Elvish code.
The difference between struct maps and maps is convenience for Go code; they
also have different performance characteristics, but since struct maps are
always quite small, the difference is not meaningful for Elvish's use cases.

As a result, there is no good reason that Elvish code needs to be aware of the
difference between struct maps and normal maps. Making them indistinguishable to
Elvish code simplifies the language.

This commit does the following:

- Change Equal, Hash, Kind and Repr to treat struct maps like maps.

- Change Assoc and Dissoc to "promote" struct maps to maps.

- Remove the custom Repr method of parse.Source.

- Update documentation to reflect this change.
2023-07-14 23:57:38 +01:00

36 lines
725 B
Go

package vals
import (
"reflect"
"src.elv.sh/pkg/persistent/vector"
)
// Lener wraps the Len method.
type Lener interface {
// Len computes the length of the receiver.
Len() int
}
var _ Lener = vector.Vector(nil)
// Len returns the length of the value, or -1 if the value does not have a
// well-defined length. It is implemented for the builtin type string, StructMap
// types, and types satisfying the Lener interface. For other types, it returns
// -1.
func Len(v any) int {
switch v := v.(type) {
case string:
return len(v)
case Lener:
return v.Len()
case StructMap:
return lenStructMap(v)
}
return -1
}
func lenStructMap(m StructMap) int {
return getStructMapInfo(reflect.TypeOf(m)).filledFields
}