github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/pkg/struct/struct.go (about) 1 // Copyright 2019 CUE Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package struct defines utilities for struct types. 16 package structs 17 18 import ( 19 "github.com/joomcode/cue/cue" 20 "github.com/joomcode/cue/cue/errors" 21 "github.com/joomcode/cue/cue/token" 22 "github.com/joomcode/cue/internal/core/adt" 23 ) 24 25 // MinFields validates the minimum number of fields that are part of a struct. 26 // It can only be used as a validator, for instance `MinFields(3)`. 27 // 28 // Only fields that are part of the data model count. This excludes hidden 29 // fields, optional fields, and definitions. 30 func MinFields(object *cue.Struct, n int) *adt.Bottom { 31 iter := object.Fields(cue.Hidden(false), cue.Optional(false)) 32 count := 0 33 for iter.Next() { 34 count++ 35 } 36 if count < n { 37 return &adt.Bottom{ 38 Code: adt.IncompleteError, // could still be resolved 39 Err: errors.Newf(token.NoPos, "len(fields) < MinFields(%[2]d) (%[1]d < %[2]d)", count, n), 40 } 41 } 42 return nil 43 } 44 45 // MaxFields validates the maximum number of fields that are part of a struct. 46 // It can only be used as a validator, for instance `MaxFields(3)`. 47 // 48 // Only fields that are part of the data model count. This excludes hidden 49 // fields, optional fields, and definitions. 50 func MaxFields(object *cue.Struct, n int) (bool, error) { 51 iter := object.Fields(cue.Hidden(false), cue.Optional(false)) 52 count := 0 53 for iter.Next() { 54 count++ 55 } 56 // permanent error is okay here. 57 return count <= n, nil 58 }