OR-Tools  8.2
recordio.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 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 
14 #include "ortools/base/recordio.h"
15 
16 #include <zlib.h>
17 
18 #include <memory>
19 #include <string>
20 
21 #include "ortools/base/logging.h"
22 
23 namespace recordio {
24 const int RecordWriter::kMagicNumber = 0x3ed7230a;
25 
27  : file_(file), use_compression_(true) {}
28 
29 bool RecordWriter::Close() { return file_->Close(); }
30 
31 void RecordWriter::set_use_compression(bool use_compression) {
32  use_compression_ = use_compression;
33 }
34 
35 std::string RecordWriter::Compress(std::string const& s) const {
36  const unsigned long source_size = s.size(); // NOLINT
37  const char* source = s.c_str();
38 
39  unsigned long dsize = source_size + (source_size * 0.1f) + 16; // NOLINT
40  std::unique_ptr<char[]> destination(new char[dsize]);
41  // Use compress() from zlib.h.
42  const int result =
43  compress(reinterpret_cast<unsigned char*>(destination.get()), &dsize,
44  reinterpret_cast<const unsigned char*>(source), source_size);
45 
46  if (result != Z_OK) {
47  LOG(FATAL) << "Compress error occurred! Error code: " << result;
48  }
49  return std::string(destination.get(), dsize);
50 }
51 
53 
54 bool RecordReader::Close() { return file_->Close(); }
55 
56 void RecordReader::Uncompress(const char* const source, uint64 source_size,
57  char* const output_buffer,
58  uint64 output_size) const {
59  unsigned long result_size = output_size; // NOLINT
60  // Use uncompress() from zlib.h
61  const int result =
62  uncompress(reinterpret_cast<unsigned char*>(output_buffer), &result_size,
63  reinterpret_cast<const unsigned char*>(source), source_size);
64  if (result != Z_OK) {
65  LOG(FATAL) << "Uncompress error occurred! Error code: " << result;
66  }
67  CHECK_LE(result_size, static_cast<unsigned long>(output_size)); // NOLINT
68 }
69 } // namespace recordio
#define LOG(severity)
Definition: base/logging.h:420
#define CHECK_LE(val1, val2)
Definition: base/logging.h:699
Definition: base/file.h:32
bool Close()
Definition: file.cc:48
RecordReader(File *const file)
Definition: recordio.cc:52
static const int kMagicNumber
Definition: recordio.h:36
RecordWriter(File *const file)
Definition: recordio.cc:26
void set_use_compression(bool use_compression)
Definition: recordio.cc:31
uint64_t uint64
const int FATAL
Definition: log_severity.h:32
Definition: file.cc:141