Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
recordio.cc
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
15
16#include <zlib.h>
17
18#include <cstdint>
19#include <memory>
20#include <string>
21
22#include "absl/log/check.h"
23#include "absl/log/log.h"
24#include "ortools/base/file.h"
25
26namespace recordio {
27const int RecordWriter::kMagicNumber = 0x3ed7230a;
28
29RecordWriter::RecordWriter(File* file) : file_(file), use_compression_(true) {}
30
31bool RecordWriter::Close() { return file_->Close(file::Defaults()).ok(); }
32
33void RecordWriter::set_use_compression(bool use_compression) {
34 use_compression_ = use_compression;
35}
36
37std::string RecordWriter::Compress(std::string const& s) const {
38 const unsigned long source_size = s.size(); // NOLINT
39 const char* source = s.c_str();
40
41 unsigned long dsize = source_size + (source_size * 0.1f) + 16; // NOLINT
42 std::unique_ptr<char[]> destination(new char[dsize]);
43 // Use compress() from zlib.h.
44 const int result =
45 compress(reinterpret_cast<unsigned char*>(destination.get()), &dsize,
46 reinterpret_cast<const unsigned char*>(source), source_size);
47
48 if (result != Z_OK) {
49 LOG(FATAL) << "Compress error occurred! Error code: " << result;
50 }
51 return std::string(destination.get(), dsize);
52}
53
55
56bool RecordReader::Close() { return file_->Close(file::Defaults()).ok(); }
57
58void RecordReader::Uncompress(const char* const source, uint64_t source_size,
59 char* const output_buffer,
60 uint64_t output_size) const {
61 unsigned long result_size = output_size; // NOLINT
62 // Use uncompress() from zlib.h
63 const int result =
64 uncompress(reinterpret_cast<unsigned char*>(output_buffer), &result_size,
65 reinterpret_cast<const unsigned char*>(source), source_size);
66 if (result != Z_OK) {
67 LOG(FATAL) << "Uncompress error occurred! Error code: " << result;
68 }
69 CHECK_LE(result_size, static_cast<unsigned long>(output_size)); // NOLINT
70}
71} // namespace recordio
Definition file.h:30
RecordReader(File *const file)
Definition recordio.cc:54
void set_use_compression(bool use_compression)
Definition recordio.cc:33
static const int kMagicNumber
Definition recordio.h:36
RecordWriter(File *file)
Definition recordio.cc:29
Definition file.cc:327
Options Defaults()
Definition file.h:86