Evan Stade | 416f46f1 | 2025-06-18 15:42:39 | [diff] [blame] | 1 | // Copyright 2025 The Chromium Authors |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include"sql/streaming_blob_handle.h" |
| 6 | |
| 7 | #include<stdint.h> |
| 8 | |
| 9 | #include<utility> |
| 10 | |
| 11 | #include"base/check.h" |
| 12 | #include"base/containers/span.h" |
| 13 | #include"base/functional/callback.h" |
| 14 | #include"base/numerics/safe_conversions.h" |
| 15 | #include"base/types/pass_key.h" |
| 16 | #include"sql/sqlite_result_code.h" |
| 17 | #include"third_party/sqlite/sqlite3.h" |
| 18 | |
| 19 | namespace sql{ |
| 20 | |
| 21 | StreamingBlobHandle::StreamingBlobHandle( |
| 22 | base::PassKey<sql::Database>, |
| 23 | sqlite3_blob* blob, |
| 24 | base::OnceCallback<void(SqliteResultCode,constchar*)> done_callback) |
| 25 | : blob_handle_(blob), done_callback_(std::move(done_callback)){ |
| 26 | CHECK(blob); |
| 27 | CHECK(done_callback_); |
| 28 | } |
| 29 | |
| 30 | StreamingBlobHandle::~StreamingBlobHandle(){ |
| 31 | if(blob_handle_){ |
| 32 | int result= sqlite3_blob_close(blob_handle_.ExtractAsDangling()); |
| 33 | std::move(done_callback_) |
| 34 | .Run(ToSqliteResultCode(result),"-- sqlite3_blob_close()"); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | StreamingBlobHandle::StreamingBlobHandle(StreamingBlobHandle&& other) |
| 39 | : blob_handle_(std::exchange(other.blob_handle_,nullptr)), |
| 40 | done_callback_(std::move(other.done_callback_)){} |
| 41 | |
| 42 | boolStreamingBlobHandle::Read(int offset, base::span<uint8_t> into){ |
| 43 | CHECK(blob_handle_); |
| 44 | int result= sqlite3_blob_read(blob_handle_, into.data(), |
| 45 | base::checked_cast<int>(into.size()), offset); |
| 46 | if(result!= SQLITE_OK)[[unlikely]]{ |
| 47 | sqlite3_blob_close(blob_handle_.ExtractAsDangling()); |
| 48 | std::move(done_callback_) |
| 49 | .Run(ToSqliteResultCode(result),"-- sqlite3_blob_read()"); |
| 50 | // `this` could be deleted. |
| 51 | returnfalse; |
| 52 | } |
| 53 | returntrue; |
| 54 | } |
| 55 | |
| 56 | boolStreamingBlobHandle::Write(int offset, base::span<constuint8_t> from){ |
| 57 | CHECK(blob_handle_); |
| 58 | int result= sqlite3_blob_write(blob_handle_, from.data(), |
| 59 | base::checked_cast<int>(from.size()), offset); |
| 60 | if(result!= SQLITE_OK)[[unlikely]]{ |
| 61 | sqlite3_blob_close(blob_handle_.ExtractAsDangling()); |
| 62 | std::move(done_callback_) |
| 63 | .Run(ToSqliteResultCode(result),"-- sqlite3_blob_write()"); |
| 64 | // `this` could be deleted. |
| 65 | returnfalse; |
| 66 | } |
| 67 | returntrue; |
| 68 | } |
| 69 | |
| 70 | }// namespace sql |