1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef OTS_MEMORY_STREAM_H_
6 #define OTS_MEMORY_STREAM_H_
11 #include "opentype-sanitiser.h"
15 class MemoryStream
: public OTSStream
{
17 MemoryStream(void *ptr
, size_t length
)
18 : ptr_(ptr
), length_(length
), off_(0) {
21 virtual bool WriteRaw(const void *data
, size_t length
) {
22 if ((off_
+ length
> length_
) ||
23 (length
> std::numeric_limits
<size_t>::max() - off_
)) {
26 std::memcpy(static_cast<char*>(ptr_
) + off_
, data
, length
);
31 virtual bool Seek(off_t position
) {
32 if (position
< 0) return false;
33 if (static_cast<size_t>(position
) > length_
) return false;
38 virtual off_t
Tell() const {
48 class ExpandingMemoryStream
: public OTSStream
{
50 ExpandingMemoryStream(size_t initial
, size_t limit
)
51 : length_(initial
), limit_(limit
), off_(0) {
52 ptr_
= new uint8_t[length_
];
55 ~ExpandingMemoryStream() {
56 delete[] static_cast<uint8_t*>(ptr_
);
63 bool WriteRaw(const void *data
, size_t length
) {
64 if ((off_
+ length
> length_
) ||
65 (length
> std::numeric_limits
<size_t>::max() - off_
)) {
66 if (length_
== limit_
)
68 size_t new_length
= (length_
+ 1) * 2;
69 if (new_length
< length_
)
71 if (new_length
> limit_
)
73 uint8_t* new_buf
= new uint8_t[new_length
];
74 std::memcpy(new_buf
, ptr_
, length_
);
76 delete[] static_cast<uint8_t*>(ptr_
);
78 return WriteRaw(data
, length
);
80 std::memcpy(static_cast<char*>(ptr_
) + off_
, data
, length
);
85 bool Seek(off_t position
) {
86 if (position
< 0) return false;
87 if (static_cast<size_t>(position
) > length_
) return false;
105 #endif // OTS_MEMORY_STREAM_H_