1 // Copyright 2014 The Android Open Source Project
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 #pragma once
16 
17 #include "aemu/base/async/AsyncStatus.h"
18 #include "aemu/base/async/Looper.h"
19 
20 #include <stdint.h>
21 
22 namespace android {
23 namespace base {
24 
25 // Helper class to help read data from a socket asynchronously.
26 //
27 // Call reset() to indicate how many bytes of data to read into a
28 // client-provided buffer, and a Looper::FdWatch to use.
29 //
30 // Then in the FdWatch callback, call run() on i/o read events.
31 // The function returns an AsyncStatus that indicates what to do
32 // after the run.
33 //
34 // Usage example:
35 //
36 //     AsyncReader myReader;
37 //     myReader.reset(myBuffer, sizeof myBuffer, myFdWatch);
38 //     ...
39 //     // when an event happens on myFdWatch
40 //     AsyncStatus status = myReader.run();
41 //     if (status == kCompleted) {
42 //         // finished reading the data.
43 //     } else if (status == kError) {
44 //         // i/o error (i.e. socket disconnection).
45 //     } else {  // really |status == kAgain|
46 //         // still more data needed to fill the buffer.
47 //     }
48 //
49 class AsyncReader {
50 public:
AsyncReader()51     AsyncReader() :
52             mBuffer(NULL),
53             mBufferSize(0U),
54             mPos(0),
55             mFdWatch(NULL) {}
56 
57     void reset(void* buffer, size_t buffSize, Looper::FdWatch* watch);
58 
59     AsyncStatus run();
60 
61 private:
62     uint8_t* mBuffer;
63     size_t mBufferSize;
64     size_t mPos;
65     Looper::FdWatch* mFdWatch;
66 };
67 
68 }  // namespace base
69 }  // namespace android
70