[PATCH go-jmap v1] jmap: expose ID::Valid() function
Export this patch
A consumer cannot be aware of whether or not an ID is valid otherwise.
Signed-off-by: Tristan Partin <tristan@partin.io>
---
Thanks! Applied.
jmap.go | 16 +++++++++++++---
jmap_test.go | 31 +++++++++++++++++++++++++++++++
2 files changed, 44 insertions(+), 3 deletions(-)
create mode 100644 jmap_test.go
diff --git a/jmap.go b/jmap.go
index b074f2c..30edec2 100644
--- a/jmap.go
+++ b/jmap.go
@@ -20,12 +20,22 @@ type ID string
var idRegexp = regexp.MustCompile(`^[A-Za-z0-9\-_]+$`)
-func (id ID) MarshalJSON() ([]byte, error) {
+// Valid checks to make sure that the given ID is valid according to the
+// specification.
+func (id ID) Valid() (bool, error) {
if len(string(id)) < 1 {
- return nil, fmt.Errorf("invalid ID: too short")
+ return false, fmt.Errorf("invalid ID: too short")
}
if len(string(id)) > 255 {
- return nil, fmt.Errorf("invalid ID: too long")
+ return false, fmt.Errorf("invalid ID: too long")
+ }
+
+ return true, nil
+}
+
+func (id ID) MarshalJSON() ([]byte, error) {
+ if _, err := id.Valid(); err != nil {
+ return nil, err
}
return json.Marshal(string(id))
}
diff --git a/jmap_test.go b/jmap_test.go
new file mode 100644
index 0000000..9aa717f
--- /dev/null
+++ b/jmap_test.go
@@ -0,0 +1,31 @@
+package jmap
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestIdLength(t *testing.T) {
+ cases := []struct {
+ id string
+ valid bool
+ }{
+ {
+ id: "",
+ valid: false,
+ },
+ {
+ // Length 256
+ id: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV",
+ valid: false,
+ },
+ }
+
+ for _, c := range cases {
+ id := ID(c.id)
+
+ ok, err := id.Valid()
+ assert.Equal(t, ok, c.valid, "%v", err)
+ }
+}
--
Tristan Partin
https://tristan.partin.io