@@ -80,28 +80,68 @@ func TestDecode(t *testing.T) {
80
80
}
81
81
82
82
func TestRoundTrip (t * testing.T ) {
83
- buf := make ([]byte , 17 )
84
- rand .Read (buf )
83
+ buf := make ([]byte , 37 + 16 ) // sufficiently large prime number of bytes (37) + another 16 to test leading 0s
84
+ rand .Read (buf [ 16 :] )
85
85
86
- baseList := [] Encoding { Identity , Base16 , Base32 , Base32hex , Base32pad , Base32hexPad , Base58BTC , Base58Flickr , Base64pad , Base64urlPad }
86
+ for base := range EncodingToStr {
87
87
88
- for _ , base := range baseList {
89
- enc , err := Encode (base , buf )
90
- if err != nil {
91
- t .Fatal (err )
92
- }
88
+ // test roundtrip from the full zero-prefixed buffer down to a single byte
89
+ for i := 0 ; i <= len (buf )- 1 ; i ++ {
93
90
94
- e , out , err := Decode (enc )
95
- if err != nil {
96
- t .Fatal (err )
97
- }
91
+ // use a copy to verify we are not overwriting the supplied buffer
92
+ newBuf := make ([]byte , len (buf )- i )
93
+ copy (newBuf , buf [i :])
98
94
99
- if e != base {
100
- t .Fatal ("got wrong encoding out" )
101
- }
95
+ enc , err := Encode (base , newBuf )
96
+ if err != nil {
97
+ t .Fatal (err )
98
+ }
99
+
100
+ e , out , err := Decode (enc )
101
+ if err != nil {
102
+ t .Fatal (err )
103
+ }
102
104
103
- if ! bytes .Equal (buf , out ) {
104
- t .Fatal ("input wasnt the same as output" , buf , out )
105
+ if e != base {
106
+ t .Fatal ("got wrong encoding out" )
107
+ }
108
+
109
+ if ! bytes .Equal (newBuf , buf [i :]) {
110
+ t .Fatal ("the provided buffer was modified" , buf [i :], out )
111
+ }
112
+
113
+ if ! bytes .Equal (buf [i :], out ) {
114
+ t .Fatal ("input wasnt the same as output" , buf [i :], out )
115
+ }
116
+
117
+ // When we have 3 leading zeroes, and this is a case-insensitive codec
118
+ // semi-randomly swap case in enc and try again
119
+ if i == 13 {
120
+ name := EncodingToStr [base ]
121
+ if name [len (name )- 5 :] == "upper" || Encodings [name + "upper" ] > 0 {
122
+ caseTamperedEnc := []byte (enc )
123
+
124
+ for _ , j := range []int {3 , 5 , 8 , 13 , 21 , 23 , 29 } {
125
+ if caseTamperedEnc [j ] >= 65 && caseTamperedEnc [j ] <= 90 {
126
+ caseTamperedEnc [j ] += 32
127
+ } else if caseTamperedEnc [j ] >= 97 && caseTamperedEnc [j ] <= 122 {
128
+ caseTamperedEnc [j ] -= 32
129
+ }
130
+ }
131
+
132
+ e , out , err := Decode (string (caseTamperedEnc ))
133
+ if err != nil {
134
+ t .Fatal (err )
135
+ }
136
+
137
+ if e != base {
138
+ t .Fatal ("got wrong encoding out" )
139
+ }
140
+ if ! bytes .Equal (buf [i :], out ) {
141
+ t .Fatal ("input wasnt the same as output" , buf [i :], out )
142
+ }
143
+ }
144
+ }
105
145
}
106
146
}
107
147
0 commit comments