使用流式函数解决v语言zstd程序解压缩失败问题

上文的简易压缩/解压程序在解压缩较大文件时出错,输出到文件为0字节。

bash 复制代码
请输入要解压的.zst文件路径: vzstd.zst
请输入解压后文件保存路径: var.txt
正在解压 vzstd.zst...
解压完成!
压缩文件: vzstd.zst (88089043 字节)
解压文件: var.txt (0 字节)        <---------------no data in output file
耗时: 0.43 秒

我在github上提出此问题

kbkpbot 回答如下

os.write_bytes(output_file, decompressed_data)
For small zstd file, you can use compress()/decompress() directly.

For large zstd file, because V internal array size limit(it use int which has a limit), you can't use a supper large buffer now, I suggest use a stream mode compress/decompress.

并提供了解决此问题的具体改用流式函数实现,

c 复制代码
const buf_in_size = 1024 * 1024
const buf_out_size = 1024 * 1024

fn decompress_file_fun(fname string, oname string, params zstd.DecompressParams) ! {
	mut fin := os.open_file(fname, 'rb')!
	mut fout := os.open_file(oname, 'wb')!
	defer {
		fin.close()
		fout.close()
	}

	mut buf_in := []u8{len: buf_in_size}
	mut buf_out := []u8{len: buf_out_size}

	mut dctx := zstd.new_dctx(params)!
	defer {
		dctx.free_dctx()
	}

	mut input := &zstd.InBuffer{
		src:  buf_in.data
		size: 0
		pos:  0
	}
	mut output := &zstd.OutBuffer{
		dst:  buf_out.data
		size: 0
		pos:  0
	}

	mut last_ret := usize(0)
	for {
		read_len := fin.read(mut buf_in)!
		input.src = buf_in.data
		input.size = usize(read_len)
		input.pos = 0
		for input.pos < input.size {
			output.dst = buf_out.data
			output.size = buf_out_size
			output.pos = 0
			ret := dctx.decompress_stream(output, input)!
			fout.write(buf_out[..output.pos])!
			last_ret = ret
		}
		if read_len < buf_in.len {
			break
		}
	}
	if last_ret != 0 {
		/* The last return value from DecompressStream did not end on a
         * frame, but we reached the end of the file! We assume this is an
         * error, and the input was truncated.
         */
		return error('EOF before end of stream: ${last_ret}')
	}
}

将此函数添加到源代码,并在decompress_file函数中用如下语句调用代替原有解压缩部分代码。

c 复制代码
    println("正在解压 ${input_file}...")
    start_time := time.now()

    decompress_file_fun(input_file, output_file)or {} //or {}必须,否则编译出错

    duration := time.since(start_time).seconds()

这样就可以解压缩完成了

c 复制代码
v -prod vzstd2.v

./vzstd2
ZSTD 压缩/解压工具
1. 压缩文件
2. 解压文件
3. 退出程序
请选择操作 (1-3): 2
请输入要解压的.zst文件路径: vzstd2.zst
请输入解压后文件保存路径: ccc.txt
正在解压 vzstd2.zst...
解压完成!
压缩文件: vzstd2.zst (88089043 字节)
解压文件: ccc.txt (106046919 字节)
耗时: 0.78 秒
相关推荐
Fairy要carry14 小时前
面试-Agent Loop
前端·chrome
Surmon17 小时前
基于 Cloudflare 生态的 AI Agent 实现
前端·人工智能·架构
六月June June21 小时前
自定义调色盘组件
前端·javascript·调色盘
SY_FC1 天前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
糟糕好吃1 天前
我让 AI 操作网页之后,开始不想点按钮了
前端·javascript·后端
陈天伟教授1 天前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
VaJoy1 天前
给到夯!前端工具链新标杆 Vite Plus 初探
前端·vite
小彭努力中1 天前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium
奇舞精选1 天前
用去年 github 最火的 n8n 快速实现自动化推送工具
前端·agent
奇舞精选1 天前
实践:如何为智能体推理引入外部决策步骤
前端·agent