scc 2026.07
SystemC components library
xz_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 "xz_streambuf.h"
18#include <cstdint>
19
20util::xz_streambuf::xz_streambuf(const std::string& path)
21: file_(fopen(path.c_str(), "rb"))
22, buffer_(64 * 1024)
23, inbuf_(64 * 1024) {
24 if(!file_)
25 throw std::runtime_error("fopen failed");
26
27 auto res = lzma_stream_decoder(&strm_, UINT64_MAX, 0);
28 if(res != LZMA_OK)
29 throw std::runtime_error("initialization of lzma_stream failed");
30 setg(buffer_.data(), buffer_.data(), buffer_.data());
31}
32
33util::xz_streambuf::~xz_streambuf() {
34 lzma_end(&strm_);
35 if(file_)
36 fclose(file_);
37}
38
39auto util::xz_streambuf::underflow() -> int_type {
40 strm_.next_out = reinterpret_cast<uint8_t*>(buffer_.data());
41 strm_.avail_out = buffer_.size();
42 while(strm_.avail_out > 0) {
43 if(strm_.avail_in == 0) {
44 strm_.next_in = reinterpret_cast<uint8_t*>(inbuf_.data());
45 strm_.avail_in = fread(inbuf_.data(), 1, inbuf_.size(), file_);
46 if(strm_.avail_in == 0)
47 break;
48 }
49 lzma_ret ret = lzma_code(&strm_, LZMA_RUN);
50 if(ret == LZMA_STREAM_END)
51 break;
52
53 if(ret != LZMA_OK)
54 return traits_type::eof();
55 }
56 size_t produced = buffer_.size() - strm_.avail_out;
57 if(produced == 0)
58 return traits_type::eof();
59
60 setg(buffer_.data(), buffer_.data(), buffer_.data() + produced);
61 return traits_type::to_int_type(*gptr());
62}