scc 2026.07
SystemC components library
bzip2_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 "bzip2_streambuf.h"
18
19util::bzip2_streambuf::bzip2_streambuf(const std::string& path)
20: file_(fopen(path.c_str(), "rb"))
21, buffer_(64 * 1024) {
22 if(!file_)
23 throw std::runtime_error("fopen failed");
24
25 bz_ = BZ2_bzReadOpen(&bzerror_, file_, 0, 0, nullptr, 0);
26 if(bzerror_ != BZ_OK)
27 throw std::runtime_error("BZ2_bzReadOpen failed");
28
29 setg(buffer_.data(), buffer_.data(), buffer_.data());
30}
31
32util::bzip2_streambuf::~bzip2_streambuf() {
33 if(bz_)
34 BZ2_bzReadClose(&bzerror_, bz_);
35
36 if(file_)
37 fclose(file_);
38}
39
40auto util::bzip2_streambuf::underflow() -> int_type {
41 int n = BZ2_bzRead(&bzerror_, bz_, buffer_.data(), buffer_.size());
42 if(bzerror_ != BZ_OK && bzerror_ != BZ_STREAM_END)
43 return traits_type::eof();
44
45 if(n <= 0)
46 return traits_type::eof();
47
48 setg(buffer_.data(), buffer_.data(), buffer_.data() + n);
49 return traits_type::to_int_type(*gptr());
50}