1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/python/lib/io/py_record_reader.h"
17
18 #include "tensorflow/c/tf_status_helper.h"
19 #include "tensorflow/core/lib/core/stringpiece.h"
20 #include "tensorflow/core/lib/io/record_reader.h"
21 #include "tensorflow/core/lib/io/zlib_compression_options.h"
22 #include "tensorflow/core/platform/env.h"
23 #include "tensorflow/core/platform/types.h"
24
25 namespace tensorflow {
26
27 class RandomAccessFile;
28
29 namespace io {
30
PyRecordReader()31 PyRecordReader::PyRecordReader() {}
32
33 // NOTE(sethtroisi): At this time PyRecordReader doesn't benefit from taking
34 // RecordReaderOptions, if this changes the API can be updated at that time.
New(const string & filename,uint64 start_offset,const string & compression_type_string,TF_Status * out_status)35 PyRecordReader* PyRecordReader::New(const string& filename, uint64 start_offset,
36 const string& compression_type_string,
37 TF_Status* out_status) {
38 std::unique_ptr<RandomAccessFile> file;
39 Status s = Env::Default()->NewRandomAccessFile(filename, &file);
40 if (!s.ok()) {
41 Set_TF_Status_from_Status(out_status, s);
42 return nullptr;
43 }
44 PyRecordReader* reader = new PyRecordReader;
45 reader->offset_ = start_offset;
46 reader->file_ = file.release();
47
48 static const uint64 kReaderBufferSize = 16 * 1024 * 1024;
49 RecordReaderOptions options =
50 RecordReaderOptions::CreateRecordReaderOptions(compression_type_string);
51 options.buffer_size = kReaderBufferSize;
52 reader->reader_ = new RecordReader(reader->file_, options);
53 return reader;
54 }
55
~PyRecordReader()56 PyRecordReader::~PyRecordReader() {
57 delete reader_;
58 delete file_;
59 }
60
GetNext(TF_Status * status)61 void PyRecordReader::GetNext(TF_Status* status) {
62 if (reader_ == nullptr) {
63 Set_TF_Status_from_Status(status,
64 errors::FailedPrecondition("Reader is closed."));
65 return;
66 }
67 Status s = reader_->ReadRecord(&offset_, &record_);
68 Set_TF_Status_from_Status(status, s);
69 }
70
Close()71 void PyRecordReader::Close() {
72 delete reader_;
73 delete file_;
74 file_ = nullptr;
75 reader_ = nullptr;
76 }
77
78 } // namespace io
79 } // namespace tensorflow
80