2018-05-22 17:56:55 +00:00
|
|
|
package checker
|
|
|
|
|
|
|
|
import (
|
2018-09-28 13:58:30 +00:00
|
|
|
"errors"
|
2018-10-01 17:27:38 +00:00
|
|
|
"git.xdrm.io/go/aicra/driver"
|
2018-05-22 17:56:55 +00:00
|
|
|
)
|
|
|
|
|
2018-09-28 13:58:30 +00:00
|
|
|
var ErrNoMatchingType = errors.New("no matching type")
|
|
|
|
var ErrDoesNotMatch = errors.New("does not match")
|
|
|
|
|
2018-05-22 17:56:55 +00:00
|
|
|
// CreateRegistry creates an empty type registry
|
2018-10-01 17:27:38 +00:00
|
|
|
func CreateRegistry() Registry {
|
|
|
|
return make(Registry)
|
2018-05-22 17:56:55 +00:00
|
|
|
}
|
|
|
|
|
2018-10-01 17:27:38 +00:00
|
|
|
// Add adds a new checker for a path
|
|
|
|
func (reg Registry) Add(_path string, _element driver.Checker) {
|
|
|
|
reg[_path] = _element
|
2018-05-22 17:56:55 +00:00
|
|
|
}
|
|
|
|
|
2018-07-08 23:34:21 +00:00
|
|
|
// Run finds a type checker from the registry matching the type @typeName
|
|
|
|
// and uses this checker to check the @value. If no type checker matches
|
|
|
|
// the @typeName name, error is returned by default.
|
2018-07-08 23:37:57 +00:00
|
|
|
func (reg Registry) Run(typeName string, value interface{}) error {
|
2018-05-22 17:56:55 +00:00
|
|
|
|
|
|
|
/* (1) Iterate to find matching type (take first) */
|
2018-10-01 17:27:38 +00:00
|
|
|
for _, t := range reg {
|
2018-05-22 17:56:55 +00:00
|
|
|
|
|
|
|
// stop if found
|
2018-07-08 23:34:21 +00:00
|
|
|
if t.Match(typeName) {
|
2018-05-22 17:56:55 +00:00
|
|
|
|
2018-10-01 17:27:38 +00:00
|
|
|
// check value
|
|
|
|
if t.Check(value) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return ErrDoesNotMatch
|
|
|
|
|
|
|
|
}
|
2018-05-22 17:56:55 +00:00
|
|
|
|
2018-05-22 18:27:51 +00:00
|
|
|
}
|
|
|
|
|
2018-10-01 17:27:38 +00:00
|
|
|
return ErrNoMatchingType
|
2018-05-22 17:56:55 +00:00
|
|
|
|
|
|
|
}
|