Home | History | Annotate | Download | only in libOpenglRender
      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 #include "ReadBuffer.h"
     17 #include <string.h>
     18 #include <assert.h>
     19 #include <limits.h>
     20 #include "ErrorLog.h"
     21 
     22 ReadBuffer::ReadBuffer(IOStream *stream, size_t bufsize)
     23 {
     24     m_size = bufsize;
     25     m_stream = stream;
     26     m_buf = (unsigned char*)malloc(m_size*sizeof(unsigned char));
     27     m_validData = 0;
     28     m_readPtr = m_buf;
     29 }
     30 
     31 ReadBuffer::~ReadBuffer()
     32 {
     33     free(m_buf);
     34 }
     35 
     36 int ReadBuffer::getData()
     37 {
     38     if ((m_validData > 0) && (m_readPtr > m_buf)) {
     39         memmove(m_buf, m_readPtr, m_validData);
     40     }
     41     // get fresh data into the buffer;
     42     size_t len = m_size - m_validData;
     43     if (len==0) {
     44         //we need to inc our buffer
     45         size_t new_size = m_size*2;
     46         unsigned char* new_buf;
     47         if (new_size < m_size) { // overflow check
     48             new_size = INT_MAX;
     49         }
     50 
     51         new_buf = (unsigned char*)realloc(m_buf, new_size);
     52         if (!new_buf) {
     53             ERR("Failed to alloc %zu bytes for ReadBuffer\n", new_size);
     54             return -1;
     55         }
     56         m_size = new_size;
     57         m_buf  = new_buf;
     58         len    = m_size - m_validData;
     59     }
     60     m_readPtr = m_buf;
     61     if (NULL != m_stream->read(m_buf + m_validData, &len)) {
     62         m_validData += len;
     63         return len;
     64     }
     65     return -1;
     66 }
     67 
     68 void ReadBuffer::consume(size_t amount)
     69 {
     70     assert(amount <= m_validData);
     71     m_validData -= amount;
     72     m_readPtr += amount;
     73 }
     74