1 // Copyright 2020 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 #include "aemu/base/files/StdioStream.h"
16
17 #include <assert.h>
18 #include <errno.h>
19
20 namespace android {
21 namespace base {
22
StdioStream(FILE * file,Ownership ownership)23 StdioStream::StdioStream(FILE* file, Ownership ownership) :
24 mFile(file), mOwnership(ownership) {}
25
StdioStream(StdioStream && other)26 StdioStream::StdioStream(StdioStream&& other)
27 : mFile(other.mFile), mOwnership(other.mOwnership) {
28 other.mFile = nullptr;
29 }
30
operator =(StdioStream && other)31 StdioStream& StdioStream::operator=(StdioStream&& other) {
32 assert(this != &other);
33 close();
34 mFile = other.mFile;
35 mOwnership = other.mOwnership;
36 other.mFile = nullptr;
37 return *this;
38 }
39
~StdioStream()40 StdioStream::~StdioStream() {
41 close();
42 }
43
read(void * buffer,size_t size)44 ssize_t StdioStream::read(void* buffer, size_t size) {
45 size_t res = ::fread(buffer, 1, size, mFile);
46 if (res < size) {
47 if (!::feof(mFile)) {
48 errno = ::ferror(mFile);
49 }
50 }
51 return static_cast<ssize_t>(res);
52 }
53
write(const void * buffer,size_t size)54 ssize_t StdioStream::write(const void* buffer, size_t size) {
55 size_t res = ::fwrite(buffer, 1, size, mFile);
56 if (res < size) {
57 if (!::feof(mFile)) {
58 errno = ::ferror(mFile);
59 }
60 }
61 return static_cast<ssize_t>(res);
62 }
63
close()64 void StdioStream::close() {
65 if (mOwnership == kOwner && mFile) {
66 ::fclose(mFile);
67 mFile = nullptr;
68 }
69 }
70
71 } // namespace base
72 } // namespace android
73