2024年1月

写工具时通常会生成ZIP文件,一般来说就传相对路径和内容就好。但是今天发现一个细节。还需要将文件所在的目录也要传进去。虽然现在的解压软件都支持不传,但是如果解压的代码不规范就会造成保存路径不存在,因为父级目录不存在:

let file: File = File::create(zip_path).unwrap();  
let mut writer: ZipWriter<File> = ZipWriter::new(file);
let options = zip::write::FileOptions::default()
    .compression_method(zip::CompressionMethod::Deflated);

// 因为这里已经将所有目录 遍历好。目录结构已经不存在的,只能通过文件路径反向还原,并使用map去重
let mut dirMap:HashMap<String, bool> = HashMap::new();

// .... 中间省略循环遍历
// 先将文件目录结构创建
let arr:Vec<&str> = path.split('/').collect();
let mut tmp_dir: String = String::new();
for i in 0..(arr.len() - 1) {
    let tmp = arr[i];
    tmp_dir.push('/');
    tmp_dir.push_str(tmp);
    if dirMap.contains_key(&tmp_dir){ // 缓存保存过的目录
        continue;
    }
    dirMap.insert(tmp_dir.clone(), true);
    writer.add_directory(&tmp_dir, options).unwrap();
}

// 将文件写入ZIP
let mut buffer = Vec::new();
let mut file = File::open(&tmp_path).unwrap();
file.read_to_end(&mut buffer).unwrap();
writer.start_file(path, options).unwrap();
writer.write_all(&buffer).unwrap();

// uuid 解码参数
const separator = '@';
const HexChars = '0123456789abcdef'.split('');
const _t = ['', '', '', ''];
const UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);
const Indices = UuidTemplate.map((x, i) => (x === '-' ? NaN : i)).filter(Number.isFinite);
const BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const values = new Array(123); // max char code in base64Keys
for (let i = 0; i < 123; ++i) { values[i] = 64; } // fill with placeholder('=') index
for (let i = 0; i < 64; ++i) { values[BASE64_KEYS.charCodeAt(i)] = i; }
const BASE64_VALUES = values;

// 将3.8的uuid解码
function decodeUuid (base64) {
    const strs = base64.split(separator);
    const uuid = strs[0];
    if (uuid.length !== 22) {
        return base64;
    }
    UuidTemplate[0] = base64[0];
    UuidTemplate[1] = base64[1];
    for (let i = 2, j = 2; i < 22; i += 2) {
        const lhs = BASE64_VALUES[base64.charCodeAt(i)];
        const rhs = BASE64_VALUES[base64.charCodeAt(i + 1)];
        UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
        UuidTemplate[Indices[j++]] = HexChars[((lhs & 3) << 2) | rhs >> 4];
        UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF];
    }
    return base64.replace(uuid, UuidTemplate.join(''));
}