forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 3
/
maybe.go
47 lines (39 loc) · 1.06 KB
/
maybe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package merkledb
import "golang.org/x/exp/slices"
// Maybe T = Some T | Nothing.
// A data wrapper that allows values to be something [Some T] or nothing [Nothing].
// Maybe is used to wrap types:
// * That can't be represented by nil.
// * That use nil as a valid value instead of an indicator of a missing value.
// For more info see https://en.wikipedia.org/wiki/Option_type
type Maybe[T any] struct {
hasValue bool
value T
}
// Returns a new Maybe[T] with the value val.
func Some[T any](val T) Maybe[T] {
return Maybe[T]{
value: val,
hasValue: true,
}
}
// Returns a new Maybe[T] with no value.
func Nothing[T any]() Maybe[T] {
return Maybe[T]{}
}
// Returns true iff [m] has a value.
func (m Maybe[T]) IsNothing() bool {
return !m.hasValue
}
// Returns the value of [m].
func (m Maybe[T]) Value() T {
return m.value
}
func Clone(m Maybe[[]byte]) Maybe[[]byte] {
if !m.hasValue {
return Nothing[[]byte]()
}
return Some(slices.Clone(m.value))
}