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 "cuelang.org/go/cue/errors" 20 "cuelang.org/go/cue/token" 21 "cuelang.org/go/internal/core/adt" 22 "cuelang.org/go/internal/pkg" 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 pkg.Struct, n int) (bool, error) { 31 count := object.Len() 32 code := adt.EvalError 33 if object.IsOpen() { 34 code = adt.IncompleteError 35 } 36 if count < n { 37 return false, pkg.ValidationError{B: &adt.Bottom{ 38 Code: code, 39 Err: errors.Newf(token.NoPos, "len(fields) < MinFields(%[2]d) (%[1]d < %[2]d)", count, n), 40 }} 41 } 42 return true, 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 pkg.Struct, n int) (bool, error) { 51 count := object.Len() 52 if count > n { 53 return false, pkg.ValidationError{B: &adt.Bottom{ 54 Code: adt.EvalError, 55 Err: errors.Newf(token.NoPos, "len(fields) > MaxFields(%[2]d) (%[1]d > %[2]d)", count, n), 56 }} 57 } 58 59 return true, nil 60 } 61