stringbuffer.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #ifndef RAPIDJSON_STRINGBUFFER_H_
  2. #define RAPIDJSON_STRINGBUFFER_H_
  3. #include "rapidjson.h"
  4. #include "internal/stack.h"
  5. namespace rapidjson {
  6. //! Represents an in-memory output stream.
  7. /*!
  8. \tparam Encoding Encoding of the stream.
  9. \tparam Allocator type for allocating memory buffer.
  10. \implements Stream
  11. */
  12. template <typename Encoding, typename Allocator = CrtAllocator>
  13. struct GenericStringBuffer {
  14. typedef typename Encoding::Ch Ch;
  15. GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
  16. void Put(Ch c) { *stack_.template Push<Ch>() = c; }
  17. void Flush() {}
  18. void Clear() { stack_.Clear(); }
  19. const Ch* GetString() const {
  20. // Push and pop a null terminator. This is safe.
  21. *stack_.template Push<Ch>() = '\0';
  22. stack_.template Pop<Ch>(1);
  23. return stack_.template Bottom<Ch>();
  24. }
  25. size_t GetSize() const { return stack_.GetSize(); }
  26. static const size_t kDefaultCapacity = 256;
  27. mutable internal::Stack<Allocator> stack_;
  28. };
  29. typedef GenericStringBuffer<UTF8<> > StringBuffer;
  30. //! Implement specialized version of PutN() with memset() for better performance.
  31. template<>
  32. inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
  33. memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
  34. }
  35. } // namespace rapidjson
  36. #endif // RAPIDJSON_STRINGBUFFER_H_