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 #include "FixedBlockWriter.h"
22
FixedBlockWriter(FixedBlockProcessor & fixedBlockProcessor)23 FixedBlockWriter::FixedBlockWriter(FixedBlockProcessor &fixedBlockProcessor)
24 : FixedBlockAdapter(fixedBlockProcessor) {}
25
26
writeToStorage(const uint8_t * buffer,int32_t numBytes)27 int32_t FixedBlockWriter::writeToStorage(const uint8_t *buffer, int32_t numBytes) {
28 int32_t bytesToStore = numBytes;
29 int32_t roomAvailable = mSize - mPosition;
30 if (bytesToStore > roomAvailable) {
31 bytesToStore = roomAvailable;
32 }
33 memcpy(&mStorage[mPosition], buffer, bytesToStore);
34 mPosition += bytesToStore;
35 return bytesToStore;
36 }
37
processVariableBlock(uint8_t * buffer,int32_t numBytes)38 AdapterProcessResult FixedBlockWriter::processVariableBlock(uint8_t *buffer, int32_t numBytes) {
39 int32_t result = 0;
40 int32_t bytesLeft = numBytes;
41 int32_t bytesProcessed = 0;
42
43 // If we already have data in storage then add to it.
44 if (mPosition > 0) {
45 int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
46 buffer += bytesWritten;
47 bytesLeft -= bytesWritten;
48 bytesProcessed += bytesWritten;
49 // If storage full then flush it out
50 if (mPosition == mSize) {
51 result = mFixedBlockProcessor.onProcessFixedBlock(mStorage.get(), mSize);
52 mPosition = 0;
53 }
54 }
55
56 // Write through if enough for a complete block.
57 while(bytesLeft > mSize && result == 0) {
58 result = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
59 if (result != 0) {
60 break;
61 }
62 buffer += mSize;
63 bytesLeft -= mSize;
64 bytesProcessed += mSize;
65 }
66
67 // Save any remaining partial block for next time.
68 if (bytesLeft > 0) {
69 writeToStorage(buffer, bytesLeft);
70 bytesProcessed += bytesLeft;
71 }
72
73 return {result, bytesProcessed};
74 }
75