gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package optional
  4. import "strconv"
  5. // Option is a generic type that can hold a value of type T or be empty (None).
  6. //
  7. // It must use the slice type to work with "chi" form values binding:
  8. // * non-existing value are represented as an empty slice (None)
  9. // * existing value is represented as a slice with one element (Some)
  10. // * multiple values are represented as a slice with multiple elements (Some), the Value is the first element (not well-defined in this case)
  11. type Option[T any] []T
  12. func None[T any]() Option[T] {
  13. return nil
  14. }
  15. func Some[T any](v T) Option[T] {
  16. return Option[T]{v}
  17. }
  18. func FromPtr[T any](v *T) Option[T] {
  19. if v == nil {
  20. return None[T]()
  21. }
  22. return Some(*v)
  23. }
  24. func FromMapLookup[K comparable, V any](m map[K]V, k K) Option[V] {
  25. if v, ok := m[k]; ok {
  26. return Some(v)
  27. }
  28. return None[V]()
  29. }
  30. func FromNonDefault[T comparable](v T) Option[T] {
  31. var zero T
  32. if v == zero {
  33. return None[T]()
  34. }
  35. return Some(v)
  36. }
  37. func (o Option[T]) Has() bool {
  38. return o != nil
  39. }
  40. func (o Option[T]) Value() T {
  41. var zero T
  42. return o.ValueOrDefault(zero)
  43. }
  44. func (o Option[T]) ValueOrDefault(v T) T {
  45. if o.Has() {
  46. return o[0]
  47. }
  48. return v
  49. }
  50. // ParseBool get the corresponding optional.Option[bool] of a string using strconv.ParseBool
  51. func ParseBool(s string) Option[bool] {
  52. v, e := strconv.ParseBool(s)
  53. if e != nil {
  54. return None[bool]()
  55. }
  56. return Some(v)
  57. }