memorybuffer.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  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
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  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.
  14. #ifndef RAPIDJSON_MEMORYBUFFER_H_
  15. #define RAPIDJSON_MEMORYBUFFER_H_
  16. #include "stream.h"
  17. #include "internal/stack.h"
  18. RAPIDJSON_NAMESPACE_BEGIN
  19. //! Represents an in-memory output byte stream.
  20. /*!
  21. This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream.
  22. It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file.
  23. Differences between MemoryBuffer and StringBuffer:
  24. 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer.
  25. 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator.
  26. \tparam Allocator type for allocating memory buffer.
  27. \note implements Stream concept
  28. */
  29. template <typename Allocator = CrtAllocator>
  30. struct GenericMemoryBuffer {
  31. typedef char Ch; // byte
  32. GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
  33. void Put(Ch c) { *stack_.template Push<Ch>() = c; }
  34. void Flush() {}
  35. void Clear() { stack_.Clear(); }
  36. void ShrinkToFit() { stack_.ShrinkToFit(); }
  37. Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
  38. void Pop(size_t count) { stack_.template Pop<Ch>(count); }
  39. const Ch* GetBuffer() const {
  40. return stack_.template Bottom<Ch>();
  41. }
  42. size_t GetSize() const { return stack_.GetSize(); }
  43. static const size_t kDefaultCapacity = 256;
  44. mutable internal::Stack<Allocator> stack_;
  45. };
  46. typedef GenericMemoryBuffer<> MemoryBuffer;
  47. //! Implement specialized version of PutN() with memset() for better performance.
  48. template<>
  49. inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) {
  50. std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c));
  51. }
  52. RAPIDJSON_NAMESPACE_END
  53. #endif // RAPIDJSON_MEMORYBUFFER_H_