1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 #pragma once
18 
19 #include <cstdint>
20 #include <string>
21 
22 #include <android/util/EncodedBuffer.h>
23 
24 namespace android {
25 namespace util {
26 
27 /**
28  * A ProtoReader on top of a file descriptor.
29  */
30 class ProtoFileReader : public ProtoReader
31 {
32 public:
33     /**
34      * Read from this file descriptor.
35      */
36     ProtoFileReader(int fd);
37 
38     /**
39      * Does NOT close the file.
40      */
41     virtual ~ProtoFileReader();
42 
43     // From ProtoReader.
44     virtual ssize_t size() const;
45     virtual size_t bytesRead() const;
46     virtual uint8_t const* readBuffer();
47     virtual size_t currentToRead();
48     virtual bool hasNext();
49     virtual uint8_t next();
50     virtual uint64_t readRawVarint();
51     virtual void move(size_t amt);
52 
53     status_t getError() const;
54 private:
55     int mFd;                // File descriptor for input.
56     status_t mStatus;       // Any errors encountered during read.
57     ssize_t mSize;          // How much total data there is, or -1 if we can't tell.
58     size_t mPos;            // How much data has been read so far.
59     size_t mOffset;         // Offset in current buffer.
60     size_t mMaxOffset;      // How much data is left to read in mBuffer.
61     const int mChunkSize;   // Size of mBuffer.
62     uint8_t mBuffer[32*1024];
63 
64     /**
65      * If there is currently more data to read in the buffer, returns true.
66      * If there is not more, then tries to read.  If more data can be read,
67      * it does so and returns true.  If there is no more data, returns false.
68      * Resets mOffset and mMaxOffset as necessary.  Does not advance mOffset.
69      */
70     bool ensure_data();
71 };
72 
73 }
74 }
75 
76