-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvalidate.go
69 lines (60 loc) · 1.7 KB
/
validate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright 2013-2014 Rocky Bernstein.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// command argument-validation routines
package repl
import "strconv"
func ArgCountOK(min int, max int, args [] string) bool {
l := len(args)-1 // strip command name from count
if l < min {
Errmsg("Too few args; need at least %d, got %d", min, l)
return false
} else if max > 0 && l > max {
Errmsg("Too many args; need at most %d, got %d", max, l)
return false
}
return true
}
type NumError struct {
bogus bool
}
func (e *NumError) Error() string {
return "generic error"
}
var genericError = &NumError{bogus: true}
func GetInt(arg string, what string, min int, max int) (int, error) {
errmsg_fmt := "Expecting integer " + what + "; got '%s'."
i, err := strconv.Atoi(arg)
if err != nil {
Errmsg(errmsg_fmt, arg)
return 0, err
}
if i < min {
Errmsg("Expecting integer value %s to be at least %d; got %d.",
what, min, i)
return 0, genericError
} else if max > 0 && i > max {
Errmsg("Expecting integer value %s to be at most %d; got %d.",
what, max, i)
return 0, genericError
}
return i, nil
}
func GetUInt(arg string, what string, min uint64, max uint64) (uint64, error) {
errmsg_fmt := "Expecting integer " + what + "; got '%s'."
i, err := strconv.ParseUint(arg, 10, 0)
if err != nil {
Errmsg(errmsg_fmt, arg)
return 0, err
}
if i < min {
Errmsg("Expecting integer value %s to be at least %d; got %d.",
what, min, i)
return 0, genericError
} else if max > 0 && i > max {
Errmsg("Expecting integer value %s to be at most %d; got %d.",
what, max, i)
return 0, genericError
}
return i, nil
}