Skip to content

Commit 8d0a179

Browse files
committed
feat: add base32 helpers
Signed-off-by: Chen Su <ghosind@gmail.com>
1 parent ef72420 commit 8d0a179

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

src/base32.ts

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ export class Base32Encoding {
8181
}
8282

8383
const { encoder, padChar } = this.getEncoderAndPadChar(options);
84-
const destLen = this.encodeLength(data.length, padChar);
84+
const destLen = this.getEncodeLength(data.length, padChar);
8585
const dest = Buffer.alloc(destLen, padChar);
8686

8787
let bits = 0;
@@ -132,10 +132,7 @@ export class Base32Encoding {
132132
}
133133

134134
const { encoder, padChar } = this.getEncoderAndPadChar(options);
135-
const cleanedLength = str.endsWith(padChar) && padChar !== ''
136-
? str.indexOf(padChar)
137-
: str.length;
138-
const destLen = Math.floor((cleanedLength * 5) / 8);
135+
const [cleanedLength, destLen] = this.getDecodeLength(str, padChar);
139136
const dest = Buffer.alloc(destLen);
140137

141138
let bits = 0;
@@ -168,14 +165,29 @@ export class Base32Encoding {
168165
* @param padChar The padding character of encoding, and empty string for no padding.
169166
* @returns The length in bytes of the base32 encoded data.
170167
*/
171-
// eslint-disable-next-line class-methods-use-this
172-
encodeLength(len: number, padChar: string): number {
168+
private getEncodeLength(len: number, padChar: string): number {
173169
if (padChar === '') {
174170
return Math.floor((len * 8 + 4) / 5);
175171
}
176172
return Math.floor(Math.floor((len + 4) / 5) * 8);
177173
}
178174

175+
/**
176+
* Returns the length in bytes of cleaned string and decoded data.
177+
*
178+
* @param str The string that to decode.
179+
* @param padChar The padding character of decoding, and empty string for no padding.
180+
* @returns The length in bytes of cleaned string and decoded data.
181+
*/
182+
private getDecodeLength(str: string, padChar: string): [number, number] {
183+
const cleanedLength = str.endsWith(padChar) && padChar !== ''
184+
? str.indexOf(padChar)
185+
: str.length;
186+
const destLen = Math.floor((cleanedLength * 5) / 8);
187+
188+
return [cleanedLength, destLen];
189+
}
190+
179191
/**
180192
* Gets encoder string and padding character by options or default values.
181193
*

0 commit comments

Comments
 (0)