|
| 1 | +// Copyright 2013 The Flutter 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 | +#include "tonic/dart_weak_persistent_value.h" |
| 6 | + |
| 7 | +#include "tonic/dart_state.h" |
| 8 | +#include "tonic/scopes/dart_isolate_scope.h" |
| 9 | + |
| 10 | +namespace tonic { |
| 11 | + |
| 12 | +DartWeakPersistentValue::DartWeakPersistentValue() : handle_(nullptr) {} |
| 13 | + |
| 14 | +DartWeakPersistentValue::~DartWeakPersistentValue() { |
| 15 | + Clear(); |
| 16 | +} |
| 17 | + |
| 18 | +void DartWeakPersistentValue::Set(DartState* dart_state, |
| 19 | + Dart_Handle object, |
| 20 | + void* peer, |
| 21 | + intptr_t external_allocation_size, |
| 22 | + Dart_HandleFinalizer callback) { |
| 23 | + TONIC_DCHECK(is_empty()); |
| 24 | + dart_state_ = dart_state->GetWeakPtr(); |
| 25 | + handle_ = Dart_NewWeakPersistentHandle(object, peer, external_allocation_size, |
| 26 | + callback); |
| 27 | +} |
| 28 | + |
| 29 | +void DartWeakPersistentValue::Clear() { |
| 30 | + if (!handle_) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + auto dart_state = dart_state_.lock(); |
| 35 | + if (!dart_state) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + if (!dart_state->IsShuttingDown()) { |
| 40 | + if (Dart_CurrentIsolateGroup()) { |
| 41 | + Dart_DeleteWeakPersistentHandle(handle_); |
| 42 | + } else { |
| 43 | + // If we are not on the mutator thread, this will fail. The caller must |
| 44 | + // ensure to be on the mutator thread. |
| 45 | + DartIsolateScope scope(dart_state->isolate()); |
| 46 | + Dart_DeleteWeakPersistentHandle(handle_); |
| 47 | + } |
| 48 | + } |
| 49 | + // If it's shutting down, the handle will be deleted already. |
| 50 | + |
| 51 | + dart_state_.reset(); |
| 52 | + handle_ = nullptr; |
| 53 | +} |
| 54 | + |
| 55 | +Dart_Handle DartWeakPersistentValue::Get() { |
| 56 | + auto dart_state = dart_state_.lock(); |
| 57 | + TONIC_DCHECK(dart_state); |
| 58 | + TONIC_DCHECK(!dart_state->IsShuttingDown()); |
| 59 | + if (!handle_) { |
| 60 | + return nullptr; |
| 61 | + } |
| 62 | + return Dart_HandleFromWeakPersistent(handle_); |
| 63 | +} |
| 64 | + |
| 65 | +} // namespace tonic |
0 commit comments