• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.get() + mPosition, buffer, bytesToStore);
34     mPosition += bytesToStore;
35     return bytesToStore;
36 }
37 
write(uint8_t * buffer,int32_t numBytes)38 int32_t FixedBlockWriter::write(uint8_t *buffer, int32_t numBytes) {
39     int32_t bytesLeft = numBytes;
40 
41     // If we already have data in storage then add to it.
42     if (mPosition > 0) {
43         int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
44         buffer += bytesWritten;
45         bytesLeft -= bytesWritten;
46         // If storage full then flush it out
47         if (mPosition == mSize) {
48             bytesWritten = mFixedBlockProcessor.onProcessFixedBlock(mStorage.get(), mSize);
49             if (bytesWritten < 0) return bytesWritten;
50             mPosition = 0;
51             if (bytesWritten < mSize) {
52                 // Only some of the data was written! This should not happen.
53                 return -1;
54             }
55         }
56     }
57 
58     // Write through if enough for a complete block.
59     while(bytesLeft > mSize) {
60         int32_t bytesWritten = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
61         if (bytesWritten < 0) return bytesWritten;
62         buffer += bytesWritten;
63         bytesLeft -= bytesWritten;
64     }
65 
66     // Save any remaining partial blocks for next time.
67     if (bytesLeft > 0) {
68         int32_t bytesWritten = writeToStorage(buffer, bytesLeft);
69         bytesLeft -= bytesWritten;
70     }
71 
72     return numBytes - bytesLeft;
73 }
74