Optimize base64.encodeMime (#20409)
* Optimize `base64.encodeMime` * 5x faster for common scenarios, 13x faster if `lineLen` <= encoded string's length or `newLine` is empty. * Changed `lineLen`'s type to `Positive` to disallow `0`. * Fix
This commit is contained in:
parent
30bd75e459
commit
f7f375f59d
1 changed files with 20 additions and 6 deletions
|
|
@ -180,7 +180,7 @@ proc encode*(s: string, safe = false): string =
|
||||||
assert encode("Hello World") == "SGVsbG8gV29ybGQ="
|
assert encode("Hello World") == "SGVsbG8gV29ybGQ="
|
||||||
encodeImpl()
|
encodeImpl()
|
||||||
|
|
||||||
proc encodeMime*(s: string, lineLen = 75, newLine = "\r\n"): string =
|
proc encodeMime*(s: string, lineLen = 75.Positive, newLine = "\r\n"): string =
|
||||||
## Encodes `s` into base64 representation as lines.
|
## Encodes `s` into base64 representation as lines.
|
||||||
## Used in email MIME format, use `lineLen` and `newline`.
|
## Used in email MIME format, use `lineLen` and `newline`.
|
||||||
##
|
##
|
||||||
|
|
@ -191,11 +191,25 @@ proc encodeMime*(s: string, lineLen = 75, newLine = "\r\n"): string =
|
||||||
## * `decode proc<#decode,string>`_ for decoding a string
|
## * `decode proc<#decode,string>`_ for decoding a string
|
||||||
runnableExamples:
|
runnableExamples:
|
||||||
assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="
|
assert encodeMime("Hello World", 4, "\n") == "SGVs\nbG8g\nV29y\nbGQ="
|
||||||
result = newStringOfCap(encodeSize(s.len))
|
template cpy(l, src, idx) =
|
||||||
for i, c in encode(s):
|
b = l
|
||||||
if i != 0 and (i mod lineLen == 0):
|
while i < b:
|
||||||
result.add(newLine)
|
result[i] = src[idx]
|
||||||
result.add(c)
|
inc i
|
||||||
|
inc idx
|
||||||
|
|
||||||
|
if s.len == 0: return
|
||||||
|
let e = encode(s)
|
||||||
|
if e.len <= lineLen or newLine.len == 0:
|
||||||
|
return e
|
||||||
|
result = newString(e.len + newLine.len * ((e.len div lineLen) - int(e.len mod lineLen == 0)))
|
||||||
|
var i, j, k, b: int
|
||||||
|
let nd = e.len - lineLen
|
||||||
|
while j < nd:
|
||||||
|
cpy(i + lineLen, e, j)
|
||||||
|
cpy(i + newLine.len, newLine, k)
|
||||||
|
k = 0
|
||||||
|
cpy(result.len, e, j)
|
||||||
|
|
||||||
proc initDecodeTable*(): array[256, char] =
|
proc initDecodeTable*(): array[256, char] =
|
||||||
# computes a decode table at compile time
|
# computes a decode table at compile time
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue