github.com/anthropics/anthropic-sdk-go@v1.70.1/internal/apijson/exactness.go (about) 1 package apijson 2 3 // exactness ranks union variants by how well the input fit. A variant 4 // whose constants all match (constHit) is picked outright; among the 5 // rest, structural fit decides. 6 type exactness struct { 7 constMatch uint32 8 constMismatch uint32 9 10 requiredMissing uint32 11 fieldErrors uint32 12 coercions uint32 13 extras fitExtra 14 } 15 16 type fitExtra uint8 17 18 const ( 19 noExtras fitExtra = iota 20 hasExtras 21 ) 22 23 func (e *exactness) noteConstMatch() { e.constMatch++ } 24 func (e *exactness) noteConstMismatch() { e.constMismatch++ } 25 func (e *exactness) noteRequiredMissing(n int) { e.requiredMissing += uint32(n) } 26 func (e *exactness) noteFieldError() { e.fieldErrors++ } 27 func (e *exactness) noteCoercion() { e.coercions++ } 28 func (e *exactness) noteExtras() { e.extras = hasExtras } 29 30 func (e exactness) constHit() bool { 31 return e.constMismatch == 0 && e.constMatch > 0 32 } 33 34 func (e exactness) perfect() bool { 35 e.constMatch = 0 36 return e == exactness{} 37 } 38 39 func (e exactness) betterThan(o exactness) bool { 40 if h, oh := e.constHit(), o.constHit(); h != oh { 41 return h 42 } 43 if e.constMatch != o.constMatch { 44 return e.constMatch > o.constMatch 45 } 46 if e.requiredMissing != o.requiredMissing { 47 return e.requiredMissing < o.requiredMissing 48 } 49 if e.fieldErrors != o.fieldErrors { 50 return e.fieldErrors < o.fieldErrors 51 } 52 if e.coercions != o.coercions { 53 return e.coercions < o.coercions 54 } 55 return e.extras < o.extras 56 } 57 58 // absorb folds a child union's fit into its parent. 59 func (e *exactness) absorb(o exactness) { 60 e.requiredMissing += o.requiredMissing 61 e.fieldErrors += o.fieldErrors 62 e.coercions += o.coercions 63 if o.extras > e.extras { 64 e.extras = o.extras 65 } 66 }