~rockorager/go-jmap

5d583251ee123bb1b0c4f0d1cc5e05532a29737d — Tristan Partin a month ago d465780 main v0.5.0
jmap: expose ID::Valid() function

A consumer cannot be aware of whether or not an ID is valid otherwise.

Signed-off-by: Tristan Partin <tristan@partin.io>
2 files changed, 44 insertions(+), 3 deletions(-)

M jmap.go
A jmap_test.go
M jmap.go => jmap.go +13 -3
@@ 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))
}

A jmap_test.go => jmap_test.go +31 -0
@@ 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)
	}
}