chunk.h 2.0 KB
Newer Older
D
"init"  
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
Y
yuyang18 已提交
16
#include <memory>
D
"init"  
dzhwinter 已提交
17
#include <string>
Y
Yu Yang 已提交
18
#include <vector>
D
"init"  
dzhwinter 已提交
19

Y
Yu Yang 已提交
20
#include "paddle/fluid/platform/macros.h"
D
dongzhihong 已提交
21 22 23 24 25 26
#include "paddle/fluid/recordio/header.h"

namespace paddle {
namespace recordio {

// A Chunk contains the Header and optionally compressed records.
D
"init"  
dzhwinter 已提交
27
class Chunk {
28
 public:
29
  Chunk() : num_bytes_(0) {}
Y
Yu Yang 已提交
30
  void Add(const std::string& buf) {
Y
Yu Yang 已提交
31
    num_bytes_ += buf.size();
Y
Yu Yang 已提交
32
    records_.emplace_back(buf);
Y
Yu Yang 已提交
33
  }
D
dongzhihong 已提交
34 35
  // dump the chunk into w, and clears the chunk and makes it ready for
  // the next add invocation.
Y
Yu Yang 已提交
36 37 38 39 40
  bool Write(std::ostream& fo, Compressor ct) const;
  void Clear() {
    records_.clear();
    num_bytes_ = 0;
  }
Y
Yu Yang 已提交
41 42 43 44 45

  // returns true if ok, false if eof
  bool Parse(std::istream& sin);
  size_t NumBytes() const { return num_bytes_; }
  size_t NumRecords() const { return records_.size(); }
Y
Yu Yang 已提交
46
  const std::string& Record(int i) const { return records_[i]; }
D
"init"  
dzhwinter 已提交
47

Y
Yu Yang 已提交
48 49
  bool Empty() const { return records_.empty(); }

50
 private:
Y
Yu Yang 已提交
51
  std::vector<std::string> records_;
D
dongzhihong 已提交
52
  // sum of record lengths in bytes.
D
"init"  
dzhwinter 已提交
53
  size_t num_bytes_;
D
dongzhihong 已提交
54
  DISABLE_COPY_AND_ASSIGN(Chunk);
D
"init"  
dzhwinter 已提交
55 56
};

Y
yuyang18 已提交
57 58 59 60 61 62 63
class ChunkParser {
 public:
  explicit ChunkParser(std::istream& sin);

  bool Init();
  std::string Next();
  bool HasNext() const;
D
"init"  
dzhwinter 已提交
64

Y
yuyang18 已提交
65 66 67 68 69 70
 private:
  Header header_;
  uint32_t pos_{0};
  std::istream& in_;
  std::unique_ptr<std::istream> compressed_stream_;
};
D
"init"  
dzhwinter 已提交
71

D
dongzhihong 已提交
72 73
}  // namespace recordio
}  // namespace paddle