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#include <stdint.h>
18#include <memory.h>
19
20#include "FixedBlockAdapter.h"
21
22#include "FixedBlockReader.h"
23
24
25FixedBlockReader::FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor)
26    : FixedBlockAdapter(fixedBlockProcessor) {
27    mPosition = mSize;
28}
29
30int32_t FixedBlockReader::open(int32_t bytesPerFixedBlock) {
31    int32_t result = FixedBlockAdapter::open(bytesPerFixedBlock);
32    mPosition = mSize; // Indicate no data in storage.
33    return result;
34}
35
36int32_t FixedBlockReader::readFromStorage(uint8_t *buffer, int32_t numBytes) {
37    int32_t bytesToRead = numBytes;
38    int32_t dataAvailable = mSize - mPosition;
39    if (bytesToRead > dataAvailable) {
40        bytesToRead = dataAvailable;
41    }
42    memcpy(buffer, mStorage + mPosition, bytesToRead);
43    mPosition += bytesToRead;
44    return bytesToRead;
45}
46
47int32_t FixedBlockReader::processVariableBlock(uint8_t *buffer, int32_t numBytes) {
48    int32_t result = 0;
49    int32_t bytesLeft = numBytes;
50    while(bytesLeft > 0 && result == 0) {
51        if (mPosition < mSize) {
52            // Use up bytes currently in storage.
53            int32_t bytesRead = readFromStorage(buffer, bytesLeft);
54            buffer += bytesRead;
55            bytesLeft -= bytesRead;
56        } else if (bytesLeft >= mSize) {
57            // Read through if enough for a complete block.
58            result = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
59            buffer += mSize;
60            bytesLeft -= mSize;
61        } else {
62            // Just need a partial block so we have to use storage.
63            result = mFixedBlockProcessor.onProcessFixedBlock(mStorage, mSize);
64            mPosition = 0;
65        }
66    }
67    return result;
68}
69
70