1 // Copyright 2018 PDFium 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.
4
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7 #include "core/fxcrt/cfx_readonlymemorystream.h"
8
9 #include <utility>
10
11 #include "core/fxcrt/fx_safe_types.h"
12
CFX_ReadOnlyMemoryStream(std::unique_ptr<uint8_t,FxFreeDeleter> data,size_t size)13 CFX_ReadOnlyMemoryStream::CFX_ReadOnlyMemoryStream(
14 std::unique_ptr<uint8_t, FxFreeDeleter> data,
15 size_t size)
16 : m_data(std::move(data)), m_span(m_data.get(), size) {}
17
CFX_ReadOnlyMemoryStream(pdfium::span<const uint8_t> span)18 CFX_ReadOnlyMemoryStream::CFX_ReadOnlyMemoryStream(
19 pdfium::span<const uint8_t> span)
20 : m_span(span) {}
21
22 CFX_ReadOnlyMemoryStream::~CFX_ReadOnlyMemoryStream() = default;
23
GetSize()24 FX_FILESIZE CFX_ReadOnlyMemoryStream::GetSize() {
25 return pdfium::base::checked_cast<FX_FILESIZE>(m_span.size());
26 }
27
ReadBlockAtOffset(void * buffer,FX_FILESIZE offset,size_t size)28 bool CFX_ReadOnlyMemoryStream::ReadBlockAtOffset(void* buffer,
29 FX_FILESIZE offset,
30 size_t size) {
31 if (!buffer || offset < 0 || size == 0)
32 return false;
33
34 FX_SAFE_SIZE_T pos = size;
35 pos += offset;
36 if (!pos.IsValid() || pos.ValueOrDie() > m_span.size())
37 return false;
38
39 auto copy_span = m_span.subspan(offset, size);
40 memcpy(buffer, copy_span.data(), copy_span.size());
41 return true;
42 }
43