~samwhited/xmpp

182a143b900b5ea78d1e1b069a497b2d11d4e887 — Sam Whited 5 years ago f9a6fc4
Add random ID generation helper function
3 files changed, 57 insertions(+), 0 deletions(-)

A internal/doc.go
A internal/idgen.go
A internal/idgen_test.go
A internal/doc.go => internal/doc.go +7 -0
@@ 0,0 1,7 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

// Package internal provides non-exported functionality used by xmpp and its
// child packages.
package internal // import "bitbucket.org/mellium/xmpp/internal"

A internal/idgen.go => internal/idgen.go +22 -0
@@ 0,0 1,22 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package internal

import (
	"crypto/rand"
	"fmt"
)

// RandomID generates a new random identifier of the given length. If the OS's
// entropy pool isn't initialized, or we can't generate random numbers for some
// other reason, panic.
func RandomID(n int) string {
	b := make([]byte, (n/2)+(n&1))
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}

	return fmt.Sprintf("%x", b)[:n]
}

A internal/idgen_test.go => internal/idgen_test.go +28 -0
@@ 0,0 1,28 @@
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package internal

import "testing"

func BenchmarkRandomIDEven(b *testing.B) {
	for n := 0; n < b.N; n++ {
		RandomID(8)
	}
}

func BenchmarkRandomIDOdd(b *testing.B) {
	for n := 0; n < b.N; n++ {
		RandomID(9)
	}
}

func TestRandomIDLength(t *testing.T) {
	for i := 0; i <= 15; i++ {
		if s := RandomID(i); len(s) != i {
			t.Logf("Expected length %d got %d", i, len(s))
			t.Fail()
		}
	}
}