akshayvadher / cuid2

Next generation guids. Secure, collision-resistant ids optimized for horizontal scaling and performance. CUID2 in Go
MIT License
4 stars 1 forks source link

Require validation of length in `cuid2.go` file #10

Closed omjogani closed 3 months ago

omjogani commented 3 months ago
func TestInvalidLength(t *testing.T) {
    tests := []int{1, 33, 0, -1}
    for _, tt := range tests {
        t.Run(fmt.Sprintf("with length %d", tt), func(t *testing.T) {
            id := CreateIdOf(tt)
            fmt.Printf("Created id %q\n", id)
            if id != "" {
                t.Errorf("len %v should be between 2 and 36", tt)
            }
        })
    }
}

This test case is passing with values currently, It should not allow values [1, >33, 0, -1] . So there needs to have validation in CreateIdOf function before returning Init() or may be in Init() function at the time of injecting len.

akshayvadher commented 3 months ago

I think we need to revert this. Asking because I tested the original library and following works there

const id = init({ length: 150 });
console.log(id());
// p0m6ycspza37iwloxpn5zw0nqtbkbcycha5mm6jlqzsu33qrlh84kmkvi41qt2w5khcddvb7a50wsczoy1o795rs75b3ifld3u

So

  1. this does not match with the original spec.
  2. since we are returning error, user cannot use this inline, they will have to define it first and then pass
    
    myFunction(CreateId()) // this won't work

id, err := CreateId() myFunction(id) // only this will work. This is cumbersome and for most cases, not required.