]> git.saurik.com Git - apple/security.git/blob - cdsa/cdsa_utilities/bufferfifo.cpp
d5818d9fd8e10fc0f4a0a1c99cf0e85c4a2b7104
[apple/security.git] / cdsa / cdsa_utilities / bufferfifo.cpp
1 /*
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
8 * using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
16 */
17
18
19 //
20 // bufferfifo - a Sink that queues data in a FIFO of buffers for retrieval
21 //
22 #include "bufferfifo.h"
23 #include <Security/memutils.h>
24
25
26 namespace Security {
27
28
29 //
30 // On destruction, throw away all queued buffers (that haven't been picked up)
31 //
32 BufferFifo::~BufferFifo()
33 {
34 while (!mBuffers.empty()) {
35 delete mBuffers.front();
36 mBuffers.pop();
37 }
38 }
39
40
41 //
42 // This is the put function of a Sink. We store the data in at most two buffers:
43 // First we append to the last (partially filled) one; then we allocate a new one
44 // (if needed) to hold the rest.
45 //
46 void BufferFifo::consume(const void *data, size_t size)
47 {
48 // step 1: fill the rearmost (partially filled) buffer
49 if (size > 0 && !mBuffers.empty()) {
50 Buffer *current = mBuffers.back();
51 size_t length = current->put(data, size);
52 data = LowLevelMemoryUtilities::increment(data, length);
53 size -= length;
54 }
55 // step 2: if there's anything left, make a new buffer and fill it
56 if (size > 0) { // not done
57 Buffer *current = new Buffer(max(bufferLength, size));
58 mBuffers.push(current);
59 assert(current->available() >= size);
60 current->put(data, size);
61 }
62 }
63
64
65 //
66 // Pull the first (FI) buffer off the queue and deliver it.
67 // We retain no memory of it; it belongs to the caller now.
68 //
69 Buffer *BufferFifo::pop()
70 {
71 assert(!mBuffers.empty());
72 Buffer *top = mBuffers.front();
73 mBuffers.pop();
74 return top;
75 }
76
77
78 } // end namespace Security