]>
git.saurik.com Git - apple/security.git/blob - cdsa/cdsa_utilities/buffers.cpp
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
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
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.
20 // buffer - simple data buffers with convenience
23 #include <Security/debugging.h>
31 // Construct an empty Buffer from newly allocated memory
33 Buffer::Buffer(size_t size
)
34 : mBase(new char[size
]), mTop(mBase
+ size
), mOwningMemory(true)
36 mStart
= mEnd
= mBase
;
41 // Construct a buffer from given memory, with given fill or ownership
43 Buffer::Buffer(void *base
, size_t size
, bool filled
, bool owned
)
44 : mBase(reinterpret_cast<char *>(base
)), mTop(mBase
+ size
), mOwningMemory(owned
)
47 mEnd
= filled
? mTop
: mBase
;
52 // Destroying a buffer deallocates its memory iff it owns it.
62 // Shuffle buffer contents to make more room.
63 // Takes minimum size needed. Returns size available.
65 size_t Buffer::shuffle(size_t needed
)
67 assert(available() < needed
); // shouldn't be called otherwise
68 size_t length
= this->length();
69 memmove(mBase
, mStart
, length
);
71 mEnd
= mStart
+ length
;
72 return min(needed
, available());
77 // Formatted append to buffer
79 void Buffer::printf(const char *format
, ...)
82 va_start(args
, format
);
83 vprintf(format
, args
);
87 void Buffer::vprintf(const char *format
, va_list args
)
89 unsigned int written
= vsnprintf(mEnd
, mTop
- mEnd
, format
, args
);
90 if (written
< available()) {
91 // overflow on formatting. Reshuffle and try again
93 written
= vsnprintf(mEnd
, available(), format
, args
);
94 assert(written
< available()); //@@@ throw here?
96 mEnd
+= written
; // note: zero terminator discarded here
100 } // end namespace Security