]> Cypherpunks repositories - gostls13.git/commitdiff
encoding/base32: add DecodeString and EncodeToString helper methods.
authorDavid Symonds <dsymonds@golang.org>
Fri, 3 Feb 2012 00:52:04 +0000 (11:52 +1100)
committerDavid Symonds <dsymonds@golang.org>
Fri, 3 Feb 2012 00:52:04 +0000 (11:52 +1100)
This makes encoding/base32 be consistent with encoding/base64.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/5615053

src/pkg/encoding/base32/base32.go
src/pkg/encoding/base32/base32_test.go

index c75c7c19d15d15dccb74536bec4420a3e1b6c614..0d3cfaac6c192fb1d7ae9a7b12f39fe462bdc95e 100644 (file)
@@ -125,6 +125,13 @@ func (enc *Encoding) Encode(dst, src []byte) {
        }
 }
 
+// EncodeToString returns the base32 encoding of src.
+func (enc *Encoding) EncodeToString(src []byte) string {
+       buf := make([]byte, enc.EncodedLen(len(src)))
+       enc.Encode(buf, src)
+       return string(buf)
+}
+
 type encoder struct {
        err  error
        enc  *Encoding
@@ -298,6 +305,13 @@ func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
        return
 }
 
+// DecodeString returns the bytes represented by the base32 string s.
+func (enc *Encoding) DecodeString(s string) ([]byte, error) {
+       dbuf := make([]byte, enc.DecodedLen(len(s)))
+       n, err := enc.Decode(dbuf, []byte(s))
+       return dbuf[:n], err
+}
+
 type decoder struct {
        err    error
        enc    *Encoding
index facf5d04eeb11dbac9c05e580729bfa1d8e612ef..6ed3ace9c7ef7af06183712b2afe276a5dae6cc1 100644 (file)
@@ -51,9 +51,8 @@ func testEqual(t *testing.T, msg string, args ...interface{}) bool {
 
 func TestEncode(t *testing.T) {
        for _, p := range pairs {
-               buf := make([]byte, StdEncoding.EncodedLen(len(p.decoded)))
-               StdEncoding.Encode(buf, []byte(p.decoded))
-               testEqual(t, "Encode(%q) = %q, want %q", p.decoded, string(buf), p.encoded)
+               got := StdEncoding.EncodeToString([]byte(p.decoded))
+               testEqual(t, "Encode(%q) = %q, want %q", p.decoded, got, p.encoded)
        }
 }
 
@@ -99,6 +98,10 @@ func TestDecode(t *testing.T) {
                testEqual(t, "Decode(%q) = %q, want %q", p.encoded,
                        string(dbuf[0:count]),
                        p.decoded)
+
+               dbuf, err = StdEncoding.DecodeString(p.encoded)
+               testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, error(nil))
+               testEqual(t, "DecodeString(%q) = %q, want %q", string(dbuf), p.decoded)
        }
 }