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(uint8_t * buffer,int32_t numBytes)27 int32_t FixedBlockWriter::writeToStorage(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 int32_t FixedBlockWriter::processVariableBlock(uint8_t *buffer, int32_t numBytes) {
39     int32_t result = 0;
40     int32_t bytesLeft = numBytes;
41 
42     // If we already have data in storage then add to it.
43     if (mPosition > 0) {
44         int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
45         buffer += bytesWritten;
46         bytesLeft -= bytesWritten;
47         // If storage full then flush it out
48         if (mPosition == mSize) {
49             result = mFixedBlockProcessor.onProcessFixedBlock(mStorage, mSize);
50             mPosition = 0;
51         }
52     }
53 
54     // Write through if enough for a complete block.
55     while(bytesLeft > mSize && result == 0) {
56         result = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
57         buffer += mSize;
58         bytesLeft -= mSize;
59     }
60 
61     // Save any remaining partial block for next time.
62     if (bytesLeft > 0) {
63         writeToStorage(buffer, bytesLeft);
64     }
65 
66     return result;
67 }
68