xref: /aosp_15_r20/external/oboe/src/common/FixedBlockReader.cpp (revision 05767d913155b055644481607e6fa1e35e2fe72c)
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 
FixedBlockReader(FixedBlockProcessor & fixedBlockProcessor)25 FixedBlockReader::FixedBlockReader(FixedBlockProcessor &fixedBlockProcessor)
26         : FixedBlockAdapter(fixedBlockProcessor) {
27     mPosition = mSize;
28 }
29 
open(int32_t bytesPerFixedBlock)30 int32_t FixedBlockReader::open(int32_t bytesPerFixedBlock) {
31     int32_t result = FixedBlockAdapter::open(bytesPerFixedBlock);
32     mPosition = 0;
33     mValid = 0;
34     return result;
35 }
36 
readFromStorage(uint8_t * buffer,int32_t numBytes)37 int32_t FixedBlockReader::readFromStorage(uint8_t *buffer, int32_t numBytes) {
38     int32_t bytesToRead = numBytes;
39     int32_t dataAvailable = mValid - mPosition;
40     if (bytesToRead > dataAvailable) {
41         bytesToRead = dataAvailable;
42     }
43     memcpy(buffer, mStorage.get() + mPosition, bytesToRead);
44     mPosition += bytesToRead;
45     return bytesToRead;
46 }
47 
read(uint8_t * buffer,int32_t numBytes)48 int32_t FixedBlockReader::read(uint8_t *buffer, int32_t numBytes) {
49     int32_t bytesRead;
50     int32_t bytesLeft = numBytes;
51     while(bytesLeft > 0) {
52         if (mPosition < mValid) {
53             // Use up bytes currently in storage.
54             bytesRead = readFromStorage(buffer, bytesLeft);
55             buffer += bytesRead;
56             bytesLeft -= bytesRead;
57         } else if (bytesLeft >= mSize) {
58             // Nothing in storage. Read through if enough for a complete block.
59             bytesRead = mFixedBlockProcessor.onProcessFixedBlock(buffer, mSize);
60             if (bytesRead < 0) return bytesRead;
61             buffer += bytesRead;
62             bytesLeft -= bytesRead;
63         } else {
64             // Just need a partial block so we have to reload storage.
65             bytesRead = mFixedBlockProcessor.onProcessFixedBlock(mStorage.get(), mSize);
66             if (bytesRead < 0) return bytesRead;
67             mPosition = 0;
68             mValid = bytesRead;
69             if (bytesRead == 0) break;
70         }
71     }
72     return numBytes - bytesLeft;
73 }
74