@@ -12,7 +12,7 @@ enum Base32 {
1212 static let crockfordsEncodingTable : [ UInt8 ] = " 0123456789ABCDEFGHJKMNPQRSTVWXYZ " . utf8. map ( { $0 } )
1313
1414 static let crockfordsDecodingTable : [ UInt8 ] = [
15- // 0 1 2 3 4 5 6 7 8 9 a b c d e f
15+ // 0 1 2 3 4 5 6 7 8 9 a b c d e f
1616 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , // 0
1717 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , // 1
1818 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , 0xff , // 2
@@ -33,43 +33,36 @@ enum Base32 {
3333
3434}
3535
36- enum Base32Error : Error {
37- case invalidCharacter
38- }
39-
4036extension Data {
4137
4238 /// Decode Crockford's Base32
4339 init ? ( base32Encoded base32String: String , using table: [ UInt8 ] = Base32 . crockfordsDecodingTable) {
44- guard base32String. unicodeScalars. allSatisfy ( { $0. isASCII } ) else {
45- return nil
46- }
47-
4840 var base32String = base32String
4941 while let last = base32String. last, last == " = " {
5042 base32String. removeLast ( )
5143 }
52- guard [ 0 , 2 , 4 , 5 , 7 ] . contains ( base32String. count % 8 ) else {
53- return nil
54- }
5544
56- let dstlen = base32String. count * 5 / 8
45+ let result : Data ? = base32String. withCString ( encodedAs: Unicode . ASCII. self) { ( src) in
46+ func _strlen( _ str: UnsafePointer < UInt8 > ) -> Int {
47+ var str = str
48+ var i = 0
49+ while str. pointee != 0 {
50+ str += 1
51+ i += 1
52+ }
53+ return i
54+ }
5755
58- var buffer = Data ( count: dstlen)
56+ let srclen = _strlen ( src)
57+ guard [ 0 , 2 , 4 , 5 , 7 ] . contains ( srclen % 8 ) else {
58+ return nil
59+ }
5960
60- let success : Bool = buffer. withUnsafeMutableBytes { ( dst: UnsafeMutablePointer < UInt8 > ) in
61- base32String. withCString ( encodedAs: Unicode . ASCII. self) { ( src) in
62- func _strlen( _ str: UnsafePointer < UInt8 > ) -> Int {
63- var str = str
64- var i = 0
65- while str. pointee != 0 {
66- str += 1
67- i += 1
68- }
69- return i
70- }
61+ let dstlen = srclen * 5 / 8
7162
72- var srcleft = _strlen ( src)
63+ var buffer = Data ( count: dstlen)
64+ let success : Bool = buffer. withUnsafeMutableBytes { ( dst: UnsafeMutablePointer < UInt8 > ) in
65+ var srcleft = srclen
7366 var srcp = src
7467
7568 var dstp = dst
@@ -112,12 +105,19 @@ extension Data {
112105
113106 return true
114107 }
108+
109+ guard success else {
110+ return nil
111+ }
112+
113+ return buffer
115114 }
116- guard success else {
115+
116+ guard let data = result else {
117117 return nil
118118 }
119119
120- self = buffer
120+ self = data
121121 }
122122
123123 /// Encode Crockford's Base32
0 commit comments