]>
git.saurik.com Git - apple/security.git/blob - libsecurity_utilities/lib/buffers.cpp
2 * Copyright (c) 2000-2001,2003-2004 Apple Computer, Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 // buffer - simple data buffers with convenience
29 #include <security_utilities/debugging.h>
37 // Construct an empty Buffer from newly allocated memory
39 Buffer::Buffer(size_t size
)
40 : mBase(new char[size
]), mTop(mBase
+ size
), mOwningMemory(true)
42 mStart
= mEnd
= mBase
;
47 // Construct a buffer from given memory, with given fill or ownership
49 Buffer::Buffer(void *base
, size_t size
, bool filled
, bool owned
)
50 : mBase(reinterpret_cast<char *>(base
)), mTop(mBase
+ size
), mOwningMemory(owned
)
53 mEnd
= filled
? mTop
: mBase
;
58 // Destroying a buffer deallocates its memory iff it owns it.
68 // Shuffle buffer contents to make more room.
69 // Takes minimum size needed. Returns size available.
71 size_t Buffer::shuffle(size_t needed
)
73 assert(available() < needed
); // shouldn't be called otherwise
74 size_t length
= this->length();
75 memmove(mBase
, mStart
, length
);
77 mEnd
= mStart
+ length
;
78 return min(needed
, available());
83 // Formatted append to buffer
85 void Buffer::printf(const char *format
, ...)
88 va_start(args
, format
);
89 vprintf(format
, args
);
93 void Buffer::vprintf(const char *format
, va_list args
)
95 unsigned int written
= vsnprintf(mEnd
, mTop
- mEnd
, format
, args
);
96 if (written
< available()) {
97 // overflow on formatting. Reshuffle and try again
99 written
= vsnprintf(mEnd
, available(), format
, args
);
100 assert(written
< available()); //@@@ throw here?
102 mEnd
+= written
; // note: zero terminator discarded here
106 } // end namespace Security