NewComparer returns the built-in comparer for a given key type. Note that only int-ish and string-ish types are supported, despite the 'comparable' constraint. Attempts to use other types will result in a panic - users should define their own Comparers for these cases.
(key K)
| 2363 | // Note that only int-ish and string-ish types are supported, despite the 'comparable' constraint. |
| 2364 | // Attempts to use other types will result in a panic - users should define their own Comparers for these cases. |
| 2365 | func NewComparer[K any](key K) Comparer[K] { |
| 2366 | // Attempt to use non-reflection based comparer first. |
| 2367 | switch (any(key)).(type) { |
| 2368 | case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, string: |
| 2369 | return &defaultComparer[K]{} |
| 2370 | } |
| 2371 | // Fallback to reflection-based comparer otherwise. |
| 2372 | // This is used when caller wraps a type around a primitive type. |
| 2373 | switch reflect.TypeOf(key).Kind() { |
| 2374 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String: |
| 2375 | return &reflectComparer[K]{} |
| 2376 | } |
| 2377 | // If no comparers match then panic. |
| 2378 | // This is a compile time issue so it should not return an error. |
| 2379 | panic(fmt.Sprintf("immutable.NewComparer: must set comparer for %T type", key)) |
| 2380 | } |
| 2381 | |
| 2382 | // defaultComparer compares two values (int-ish and string-ish types are supported). Implements Comparer. |
| 2383 | type defaultComparer[K any] struct{} |
no outgoing calls
searching dependent graphs…