1 // Tencent is pleased to support the open source community by making RapidJSON available.
3 // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
5 // Licensed under the MIT License (the "License"); you may not use this file except
6 // in compliance with the License. You may obtain a copy of the License at
8 // http://opensource.org/licenses/MIT
10 // Unless required by applicable law or agreed to in writing, software distributed
11 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
13 // specific language governing permissions and limitations under the License.
15 #ifndef RAPIDJSON_MEMORYBUFFER_H_
16 #define RAPIDJSON_MEMORYBUFFER_H_
19 #include "internal/stack.h"
21 RAPIDJSON_NAMESPACE_BEGIN
23 //! Represents an in-memory output byte stream.
25 This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream.
27 It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file.
29 Differences between MemoryBuffer and StringBuffer:
30 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer.
31 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator.
33 \tparam Allocator type for allocating memory buffer.
34 \note implements Stream concept
36 template <typename Allocator = CrtAllocator>
37 struct GenericMemoryBuffer {
38 typedef char Ch; // byte
40 GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
42 void Put(Ch c) { *stack_.template Push<Ch>() = c; }
45 void Clear() { stack_.Clear(); }
46 void ShrinkToFit() { stack_.ShrinkToFit(); }
47 Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
48 void Pop(size_t count) { stack_.template Pop<Ch>(count); }
50 const Ch* GetBuffer() const {
51 return stack_.template Bottom<Ch>();
54 size_t GetSize() const { return stack_.GetSize(); }
56 static const size_t kDefaultCapacity = 256;
57 mutable internal::Stack<Allocator> stack_;
60 typedef GenericMemoryBuffer<> MemoryBuffer;
62 //! Implement specialized version of PutN() with memset() for better performance.
64 inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) {
65 std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c));
68 RAPIDJSON_NAMESPACE_END
70 #endif // RAPIDJSON_MEMORYBUFFER_H_