]> git.saurik.com Git - apple/security.git/blob - cdsa/cdsa_utilities/buffers.cpp
Security-164.1.tar.gz
[apple/security.git] / cdsa / cdsa_utilities / buffers.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 // buffer - simple data buffers with convenience
21 //
22 #include "buffers.h"
23 #include <Security/debugging.h>
24 #include <algorithm>
25
26
27 namespace Security {
28
29
30 //
31 // Construct an empty Buffer from newly allocated memory
32 //
33 Buffer::Buffer(size_t size)
34 : mBase(new char[size]), mTop(mBase + size), mOwningMemory(true)
35 {
36 mStart = mEnd = mBase;
37 }
38
39
40 //
41 // Construct a buffer from given memory, with given fill or ownership
42 //
43 Buffer::Buffer(void *base, size_t size, bool filled, bool owned)
44 : mBase(reinterpret_cast<char *>(base)), mTop(mBase + size), mOwningMemory(owned)
45 {
46 mStart = mBase;
47 mEnd = filled ? mTop : mBase;
48 }
49
50
51 //
52 // Destroying a buffer deallocates its memory iff it owns it.
53 //
54 Buffer::~Buffer()
55 {
56 if (mOwningMemory)
57 delete[] mBase;
58 }
59
60
61 //
62 // Shuffle buffer contents to make more room.
63 // Takes minimum size needed. Returns size available.
64 //
65 size_t Buffer::shuffle(size_t needed)
66 {
67 assert(available() < needed); // shouldn't be called otherwise
68 size_t length = this->length();
69 memmove(mBase, mStart, length);
70 mStart = mBase;
71 mEnd = mStart + length;
72 return min(needed, available());
73 }
74
75
76 //
77 // Formatted append to buffer
78 //
79 void Buffer::printf(const char *format, ...)
80 {
81 va_list args;
82 va_start(args, format);
83 vprintf(format, args);
84 va_end(args);
85 }
86
87 void Buffer::vprintf(const char *format, va_list args)
88 {
89 unsigned int written = vsnprintf(mEnd, mTop - mEnd, format, args);
90 if (written < available()) {
91 // overflow on formatting. Reshuffle and try again
92 shuffle();
93 written = vsnprintf(mEnd, available(), format, args);
94 assert(written < available()); //@@@ throw here?
95 }
96 mEnd += written; // note: zero terminator discarded here
97 }
98
99
100 } // end namespace Security