memorybuffer.h 2.5 KB

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