1 /* 2 * Copyright (c) Meta Platforms, Inc. and affiliates. 3 * All rights reserved. 4 * 5 * This source code is licensed under the BSD-style license found in the 6 * LICENSE file in the root directory of this source tree. 7 */ 8 9 #pragma once 10 11 #include <executorch/runtime/core/data_loader.h> 12 #include <executorch/runtime/core/error.h> 13 #include <executorch/runtime/core/result.h> 14 #include <executorch/runtime/platform/log.h> 15 #include <memory> 16 17 namespace executorch { 18 namespace extension { 19 20 /** 21 * A DataLoader that wraps a pre-allocated buffer and shares ownership to it. 22 * The FreeableBuffers that it returns do not actually free any data. 23 * 24 * This can be used to wrap data that was allocated elsewhere. 25 */ 26 class SharedPtrDataLoader final : public executorch::runtime::DataLoader { 27 public: SharedPtrDataLoader(std::shared_ptr<void> data,size_t size)28 SharedPtrDataLoader(std::shared_ptr<void> data, size_t size) 29 : data_(data), size_(size) {} 30 31 ET_NODISCARD load(size_t offset,size_t size,ET_UNUSED const DataLoader::SegmentInfo & segment_info)32 executorch::runtime::Result<executorch::runtime::FreeableBuffer> load( 33 size_t offset, 34 size_t size, 35 ET_UNUSED const DataLoader::SegmentInfo& segment_info) const override { 36 ET_CHECK_OR_RETURN_ERROR( 37 offset + size <= size_, 38 InvalidArgument, 39 "offset %zu + size %zu > size_ %zu", 40 offset, 41 size, 42 size_); 43 return executorch::runtime::FreeableBuffer( 44 static_cast<uint8_t*>(data_.get()) + offset, size, /*free_fn=*/nullptr); 45 } 46 size()47 ET_NODISCARD executorch::runtime::Result<size_t> size() const override { 48 return size_; 49 } 50 51 private: 52 const std::shared_ptr<void> data_; 53 const size_t size_; 54 }; 55 56 } // namespace extension 57 } // namespace executorch 58 59 namespace torch { 60 namespace executor { 61 namespace util { 62 // TODO(T197294990): Remove these deprecated aliases once all users have moved 63 // to the new `::executorch` namespaces. 64 using ::executorch::extension::SharedPtrDataLoader; 65 } // namespace util 66 } // namespace executor 67 } // namespace torch 68