From f929f4ffff136689b0acd2e0e81f71fa448b9aae Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Fri, 13 Oct 2023 21:16:08 +0100 Subject: [PATCH] add slice size validation --- size.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 size.go diff --git a/size.go b/size.go new file mode 100644 index 0000000..8afe495 --- /dev/null +++ b/size.go @@ -0,0 +1,31 @@ +package validate + +import ( + "errors" +) + +// Validation error. +var ( + ErrTooFewItems = errors.New("too few items") + ErrTooManyItems = errors.New("too many items") +) + +// MaxSize validates the length of a slice as being less than or equal to a given maximum. +func MaxSize[T any](l int) func([]T) error { + return func(value []T) error { + if len(value) > l { + return ErrTooFewItems + } + return nil + } +} + +// MinSize validates the length of a slice as being greater than or equal to a given minimum. +func MinSize[T any](l int) func([]T) error { + return func(value []T) error { + if len(value) < l { + return ErrTooManyItems + } + return nil + } +}