StreamWriter.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. namespace Js
  7. {
  8. //
  9. // A simple stream writer that hides low level stream details.
  10. //
  11. // Note:
  12. // This stream writer uses an internal buffer. Must call Flush() at the end to ensure
  13. // any remained content in the internal buffer is sent to the output stream.
  14. //
  15. class StreamWriter: public ScriptContextHolder
  16. {
  17. private:
  18. HostStream *m_stream;
  19. byte *m_buffer;
  20. size_t m_current;
  21. size_t m_capacity;
  22. public:
  23. StreamWriter(ScriptContext* scriptContext, HostStream* stream)
  24. : ScriptContextHolder(scriptContext),
  25. m_stream(stream),
  26. m_buffer(nullptr),
  27. m_current(0),
  28. m_capacity(0)
  29. {
  30. }
  31. byte* GetBuffer() { return m_buffer; }
  32. size_t GetLength() { return m_current; }
  33. void Write(const void* pv, size_t cb);
  34. void WriteHostObject(void* data);
  35. template <typename T>
  36. void Write(const T& value)
  37. {
  38. if ((m_current + sizeof(T)) < m_capacity)
  39. {
  40. *(T*)(m_buffer + m_current) = value;
  41. m_current += sizeof(T);
  42. }
  43. else
  44. {
  45. Write(&value, sizeof(T));
  46. }
  47. }
  48. //_Post_satisfies_(m_cur == 0)
  49. //void Flush();
  50. scaposition_t GetPosition() const;
  51. };
  52. }