snapshot before regression test
This commit is contained in:
78
includes/base64.py
Normal file
78
includes/base64.py
Normal file
@@ -0,0 +1,78 @@
|
||||
import t, c
|
||||
|
||||
|
||||
# ==============================================
|
||||
# Base64 编解码 纯裸实现
|
||||
# ==============================================
|
||||
# Base64 编码对照表
|
||||
b64_tab: t.CArray[t.CChar, None] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
|
||||
# Base64 反向解码表,映射字符到索引值
|
||||
b64_dec_tab: t.CArray[t.CInt8T, 80] = [
|
||||
62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
|
||||
-1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
|
||||
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
|
||||
-1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
|
||||
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
|
||||
]
|
||||
|
||||
# * @brief Base64 编码
|
||||
# * @param in: 输入二进制数据
|
||||
# * @param in_len: 输入长度
|
||||
# * @param out: 输出Base64字符串缓冲区
|
||||
# * @retval 编码后字符串长度
|
||||
def b64encode(s: str, out: str) -> t.CSizeT:
|
||||
_s = t.CUInt8T(s, t.CPtr)
|
||||
length: t.CSizeT = len(s)
|
||||
i: t.CSizeT = 0
|
||||
j: t.CSizeT = 0
|
||||
val: t.CUInt32T = 0
|
||||
# 每3字节一组转4字节Base64
|
||||
for i in range(0, length, 3):
|
||||
# 拼接24bit分组
|
||||
val = ((t.CUInt32T(_s[i + 0]) << 16 ) |
|
||||
(t.CUInt32T(_s[i + 1]) << 8 if (i + 1 < length) else 0) |
|
||||
(t.CUInt32T(_s[i + 2]) << 0 if (i + 2 < length) else 0))
|
||||
# 拆分4个6bit 查表
|
||||
out[j + 0] = b64_tab[(val >> 18) & 0x3F]
|
||||
out[j + 1] = b64_tab[(val >> 12) & 0x3F]
|
||||
out[j + 2] = b64_tab[(val >> 6) & 0x3F] if (i + 1 < length) else '='
|
||||
out[j + 3] = b64_tab[(val >> 0) & 0x3F] if (i + 2 < length) else '='
|
||||
j += 4
|
||||
out[j] = '\0' # 字符串结尾
|
||||
return j
|
||||
|
||||
|
||||
# * @brief Base64 解码
|
||||
# * @param in: Base64字符串
|
||||
# * @param out: 输出二进制缓冲区
|
||||
# * @retval 解码后二进制长度
|
||||
def b64decode(s: str, out: t.CUInt8T | t.CPtr) -> t.CSizeT:
|
||||
length: t.CSizeT = len(s)
|
||||
i: t.CSizeT = 0
|
||||
j: t.CSizeT = 0
|
||||
val: t.CUInt32T = 0
|
||||
c: t.CInt
|
||||
# 每4个Base64字符还原3字节
|
||||
for i in range(0, length, 4):
|
||||
if s[i] == '=': break
|
||||
val = 0
|
||||
# 逐个解析6bit
|
||||
c = s[i] - 43
|
||||
val |= (b64_dec_tab[c] & 0x3F) << 18
|
||||
c = s[i+1] - 43
|
||||
val |= (b64_dec_tab[c] & 0x3F) << 12
|
||||
c = s[i+2] - 43
|
||||
if s[i+2] != '=': val |= (b64_dec_tab[c] & 0x3F) << 6
|
||||
c = s[i+3] - 43
|
||||
if s[i+3] != '=': val |= (b64_dec_tab[c] & 0x3F)
|
||||
# 还原3字节
|
||||
out[j] = (val >> 16) & 0xFF
|
||||
j += 1
|
||||
if s[i+2] != '=':
|
||||
out[j] = (val >> 8) & 0xFF
|
||||
j += 1
|
||||
if s[i+3] != '=':
|
||||
out[j] = val & 0xFF
|
||||
j += 1
|
||||
return j
|
||||
Reference in New Issue
Block a user