From 85046997c96cdc50726e20d0720f2c250ee5a76c Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Tue, 2 Jan 2024 18:32:18 -0800 Subject: [PATCH] tlv: add utility funcs/methods to make tlv.OptionalRecord easier to use We add a WhenSome that'll pass in the actual underlying value, and not just the record. We also add `SomeRecord` to make it easier to create TLV records w/ `Some` set. --- tlv/record_type.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tlv/record_type.go b/tlv/record_type.go index 071716835..6540f8d8e 100644 --- a/tlv/record_type.go +++ b/tlv/record_type.go @@ -102,6 +102,21 @@ func (t *OptionalRecordT[T, V]) TlvType() Type { return zeroRecord.TlvType() } +// WhenSomeV executes the given function if the optional record is present. +// This operates on the inner most type, V, which is the value of the record. +func (t *OptionalRecordT[T, V]) WhenSomeV(f func(V)) { + t.Option.WhenSome(func(r RecordT[T, V]) { + f(r.Val) + }) +} + +// SomeRecordT creates a new OptionalRecordT type from a given RecordT type. +func SomeRecordT[T TlvType, V any](record RecordT[T, V]) OptionalRecordT[T, V] { + return OptionalRecordT[T, V]{ + Option: fn.Some(record), + } +} + // ZeroRecordT returns a zero value of the RecordT type. func ZeroRecordT[T TlvType, V any]() RecordT[T, V] { var v V