scc 2026.07
SystemC components library
zstd_streambuf.cpp
1/*******************************************************************************
2 * Copyright 2026 MINRES Technologies GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *******************************************************************************/
16
17#include "zstd_streambuf.h"
18
19util::zstd_streambuf::zstd_streambuf(const std::string& path)
20: file_(fopen(path.c_str(), "rb"))
21, buffer_(64 * 1024)
22, inbuf_(64 * 1024) {
23 if(!file_)
24 throw std::runtime_error("fopen failed");
25
26 dctx_ = ZSTD_createDCtx();
27 if(!dctx_)
28 throw std::runtime_error("ZSTD_createDCtx failed");
29
30 setg(buffer_.data(), buffer_.data(), buffer_.data());
31}
32
33util::zstd_streambuf::~zstd_streambuf() {
34 if(dctx_)
35 ZSTD_freeDCtx(dctx_);
36
37 if(file_)
38 fclose(file_);
39}
40
41auto util::zstd_streambuf::underflow() -> int_type {
42 size_t inSize = fread(inbuf_.data(), 1, inbuf_.size(), file_);
43 if(inSize == 0)
44 return traits_type::eof();
45
46 size_t outSize = ZSTD_decompressDCtx(dctx_, buffer_.data(), buffer_.size(), inbuf_.data(), inSize);
47 if(ZSTD_isError(outSize))
48 return traits_type::eof();
49
50 setg(buffer_.data(), buffer_.data(), buffer_.data() + outSize);
51 return traits_type::to_int_type(*gptr());
52}