2021-01-09 21:19:40 +00:00
|
|
|
module Spectator
|
|
|
|
# Lazily stores a value.
|
|
|
|
struct Lazy(T)
|
2021-01-09 21:35:58 +00:00
|
|
|
@value : Value(T)?
|
2021-01-09 21:19:40 +00:00
|
|
|
|
|
|
|
# Retrieves the value, if it was previously fetched.
|
|
|
|
# On the first invocation of this method, it will yield.
|
|
|
|
# The block should return the value to store.
|
|
|
|
# Subsequent calls will return the same value and not yield.
|
|
|
|
def get(&block : -> T)
|
2021-01-31 01:57:29 +00:00
|
|
|
if (existing = @value)
|
|
|
|
existing.get
|
2021-01-09 21:19:40 +00:00
|
|
|
else
|
|
|
|
yield.tap do |value|
|
2021-01-09 21:35:58 +00:00
|
|
|
@value = Value.new(value)
|
2021-01-09 21:19:40 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2021-01-09 21:35:58 +00:00
|
|
|
|
|
|
|
# Wrapper for a value.
|
|
|
|
# This is intended to be used as a union with nil.
|
|
|
|
# It allows storing (caching) a nillable value.
|
|
|
|
private struct Value(T)
|
|
|
|
# Creates the wrapper.
|
|
|
|
def initialize(@value : T)
|
|
|
|
end
|
|
|
|
|
|
|
|
# Retrieves the value.
|
|
|
|
def get : T
|
|
|
|
@value
|
|
|
|
end
|
|
|
|
end
|
2021-01-09 21:19:40 +00:00
|
|
|
end
|
|
|
|
end
|