Commits

Miki Tebeka committed 3ebbc3e

Initial import

Comments (0)

Files changed (4)

+include $(GOROOT)/src/Make.inc
+
+TARG=base62
+
+GOFILES= \
+	base62.go
+
+include $(GOROOT)/src/Make.pkg
+===============================
+base62 - base62 encoding for Go
+===============================
+
+About
+=====
+Base62 encoding is usually done to create short URLs.
+
+Authors
+=======
+
+* Miki Tebeka <miki.tebeka@gmail.com>
+
+
+License
+=======
+Copyright (C) 2011 Miki Tebeka <miki.tebeka@gmail.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+
+/* base62 encoding
+
+base62 is usually used to encode short URLs.
+*/
+package base62
+
+const (
+	alphabet = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+	Version = "0.1.0"
+)
+
+/* Encode num to base62 string. 
+*/
+func Encode(num uint64) string {
+	if num == 0 {
+		return "0"
+	}
+
+	arr := []uint8{}
+	base := uint64(len(alphabet))
+
+	for num > 0 {
+		rem := num % base
+		num = num / base
+		arr = append(arr, alphabet[rem])
+	}
+
+	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
+		arr[i], arr[j] = arr[j], arr[i]
+	}
+
+	return string(arr)
+}
+package base62
+
+import (
+	"testing"
+)
+
+type testCase struct {
+	in  uint64
+	out string
+}
+
+var testCases = []testCase{
+	{0, "0"},
+	{1, "b"},
+	{22, "w"},
+	{4444, "bjG"},
+	{7777777, "6Dwb"},
+}
+
+func TestEncode(t *testing.T) {
+	for _, tc := range testCases {
+		t.Logf("Testing %d\n", tc.in)
+		if v := Encode(tc.in); v != tc.out {
+			t.Fatalf("%d decoded to %s (should be %s)", tc.in, v, tc.out)
+		}
+	}
+}