d7bff7b23c9c8db85607d1948b25b4346538db02
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / graphics / emugl / ReadBuffer.cpp
1 /*
2 * Copyright (C) 2011 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 #include "anbox/graphics/emugl/ReadBuffer.h"
18 #include "anbox/logger.h"
19
20 #include <assert.h>
21 #include <limits.h>
22 #include <string.h>
23
24 ReadBuffer::ReadBuffer(size_t bufsize) {
25   m_size = bufsize;
26   m_buf = static_cast<unsigned char*>(malloc(m_size * sizeof(unsigned char)));
27   m_validData = 0;
28   m_readPtr = m_buf;
29 }
30
31 ReadBuffer::~ReadBuffer() { free(m_buf); }
32
33 int ReadBuffer::getData(IOStream* stream) {
34   if (stream == NULL) return -1;
35   if ((m_validData > 0) && (m_readPtr > m_buf)) {
36     memmove(m_buf, m_readPtr, m_validData);
37   }
38   // get fresh data into the buffer;
39   size_t len = m_size - m_validData;
40   if (len == 0) {
41     // we need to inc our buffer
42     size_t new_size = m_size * 2;
43     unsigned char* new_buf;
44     if (new_size < m_size) {  // overflow check
45       new_size = INT_MAX;
46     }
47
48     new_buf = static_cast<unsigned char*>(realloc(m_buf, new_size));
49     if (!new_buf) {
50       ERROR("Failed to alloc %zu bytes for ReadBuffer", new_size);
51       return -1;
52     }
53     m_size = new_size;
54     m_buf = new_buf;
55     len = m_size - m_validData;
56   }
57   m_readPtr = m_buf;
58   if (NULL != stream->read(m_buf + m_validData, &len)) {
59     m_validData += len;
60     return len;
61   }
62   return -1;
63 }
64
65 void ReadBuffer::consume(size_t amount) {
66   assert(amount <= m_validData);
67   m_validData -= amount;
68   m_readPtr += amount;
69 }