memorystream.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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_MEMORYSTREAM_H_
  15. #define RAPIDJSON_MEMORYSTREAM_H_
  16. #include "rapidjson.h"
  17. RAPIDJSON_NAMESPACE_BEGIN
  18. //! Represents an in-memory input byte stream.
  19. /*!
  20. This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream.
  21. It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file.
  22. Differences between MemoryStream and StringStream:
  23. 1. StringStream has encoding but MemoryStream is a byte stream.
  24. 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source.
  25. 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4().
  26. \note implements Stream concept
  27. */
  28. struct MemoryStream {
  29. typedef char Ch; // byte
  30. MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {}
  31. Ch Peek() const { return (src_ == end_) ? '\0' : *src_; }
  32. Ch Take() { return (src_ == end_) ? '\0' : *src_++; }
  33. size_t Tell() const { return static_cast<size_t>(src_ - begin_); }
  34. Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
  35. void Put(Ch) { RAPIDJSON_ASSERT(false); }
  36. void Flush() { RAPIDJSON_ASSERT(false); }
  37. size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
  38. // For encoding detection only.
  39. const Ch* Peek4() const {
  40. return Tell() + 4 <= size_ ? src_ : 0;
  41. }
  42. const Ch* src_; //!< Current read position.
  43. const Ch* begin_; //!< Original head of the string.
  44. const Ch* end_; //!< End of stream.
  45. size_t size_; //!< Size of the stream.
  46. };
  47. RAPIDJSON_NAMESPACE_END
  48. #endif // RAPIDJSON_MEMORYBUFFER_H_