Skip to content

Commit

Permalink
Add assign and reset to buffer ref
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 700404314
  • Loading branch information
LukeBoyer authored and tensorflower-gardener committed Nov 26, 2024
1 parent bff26f2 commit 28530c0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
41 changes: 21 additions & 20 deletions tensorflow/lite/experimental/litert/cc/litert_buffer_ref.h
Original file line number Diff line number Diff line change
Expand Up @@ -293,48 +293,49 @@ class OwningBufferRef : public MutableBufferRef<ByteT> {
return WeakTupleT(this->data_, this->size_, this->offset_);
}

// Free any owned memory.
void Reset() {
Allocator()(this->data_);
Drop();
}

// Reset any existing data and copy in given ro buffer.
void Assign(const ByteT* buf, size_t size, size_t offset = 0) {
Reset();
this->size_ = size;
this->data_ = (ByteT*)Allocator()(this->size_);
std::memcpy(this->data_, buf, this->size_);
this->offset_ = offset;
}

OwningBufferRef(OwningBufferRef&& other)
: MutableBufferRef<ByteT>(other.data_, other.size_, other.offset_) {
other.data_ = nullptr;
other.size_ = 0;
other.offset_ = 0;
other.Drop();
}

OwningBufferRef& operator=(OwningBufferRef&& other) {
if (this != &other) {
Allocator()(this->data_);
Reset();
this->data_ = other.data_;
this->size_ = other.size_;
this->offset_ = other.offset_;
other.data_ = nullptr;
other.size_ = 0;
other.offset_ = 0;
other.Drop();
}
return *this;
}

OwningBufferRef(const OwningBufferRef& other)
: MutableBufferRef<ByteT>(/*data*/ (ByteT*)nullptr, other.size_,
other.offset_) {
this->data_ = (ByteT*)Allocator()(other.size_);
std::memcpy(this->data_, other.data_, other.size_);
Assign(other.data_, other.size_, other.offset_);
}

OwningBufferRef& operator=(const OwningBufferRef& other) {
Allocator()(this->data_);
this->size_ = other.size_;
this->data_ = (ByteT*)Allocator()(this->size_);
std::memcpy(this->data_, other.data_, this->size_);
this->offset_ = other.offset_;
Assign(other.data_, other.size_, other.offset_);
return *this;
}

~OwningBufferRef() override {
Allocator()(this->data_);
this->data_ = nullptr;
this->size_ = 0;
this->offset_ = 0;
}
~OwningBufferRef() override { Reset(); }

protected:
// Debug string.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,4 +320,13 @@ TEST(OwningBufferRefTest, TupleRelease) {
delete[] data;
}

TEST(OwningBufferRefTest, Assign) {
auto const_buf = MakeConstFbData(kData);
OwningBufferRef buf;
buf.Assign(const_buf.data(), const_buf.size());
buf.WriteInto("SOME");
EXPECT_EQ(buf.StrView(), "SOMERawBuffer");
EXPECT_EQ(FbBufToStr(const_buf), "SomeRawBuffer");
}

} // namespace

0 comments on commit 28530c0

Please sign in to comment.