1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use std::mem::transmute;
use std::ptr::NonNull;

use crate::Data;
use crate::HandleScope;
use crate::Isolate;
use crate::IsolateHandle;
use crate::Local;

extern "C" {
  fn v8__Local__New(isolate: *mut Isolate, other: *const Data) -> *const Data;

  fn v8__Global__New(isolate: *mut Isolate, other: *const Data) -> *const Data;

  fn v8__Global__Reset__0(this: *mut *const Data);

  fn v8__Global__Reset__2(
    this: *mut *const Data,
    isolate: *mut Isolate,
    other: *const *const Data,
  );
}

/// An object reference that is independent of any handle scope. Where
/// a Local handle only lives as long as the HandleScope in which it was
/// allocated, a global handle remains valid until it is explicitly
/// disposed using reset().
///
/// A global handle contains a reference to a storage cell within
/// the V8 engine which holds an object value and which is updated by
/// the garbage collector whenever the object is moved. A new storage
/// cell can be created using the constructor or Global::set and
/// existing handles can be disposed using Global::reset.
#[repr(C)]
pub struct Global<T> {
  value: Option<NonNull<T>>,
  isolate_handle: Option<IsolateHandle>,
}

impl<T> Global<T> {
  /// Construct a Global with no storage cell.
  pub fn new() -> Self {
    Self {
      value: None,
      isolate_handle: None,
    }
  }

  /// Construct a new Global from an existing handle. When the existing handle
  /// is non-empty, a new storage cell is created pointing to the same object,
  /// and no flags are set.
  pub fn new_from(scope: &mut Isolate, other: impl AnyHandle<T>) -> Self {
    let other_value = other.read(scope);
    Self {
      value: other_value
        .map(|v| unsafe { transmute(v8__Global__New(scope, transmute(v))) }),
      isolate_handle: other_value.map(|_| scope.thread_safe_handle()),
    }
  }

  /// Returns true if this Global is empty, i.e., has not been
  /// assigned an object.
  pub fn is_empty(&self) -> bool {
    self.value.is_none()
  }

  /// Construct a Local<T> from this global handle.
  pub fn get<'s>(
    &self,
    scope: &mut HandleScope<'s, ()>,
  ) -> Option<Local<'s, T>> {
    self.check_isolate(scope);
    self
      .value
      .map(|g| g.as_ptr() as *const Data)
      .and_then(|g| unsafe {
        scope
          .cast_local(|sd| v8__Local__New(sd.get_isolate_ptr(), g) as *const T)
      })
  }

  /// If non-empty, destroy the underlying storage cell
  /// and create a new one with the contents of other if other is non empty.
  pub fn set(&mut self, scope: &mut Isolate, other: impl AnyHandle<T>) {
    self.check_isolate(scope);
    let other_value = other.read(scope);
    match (&mut self.value, &other_value) {
      (None, None) => {}
      (target, None) => unsafe {
        v8__Global__Reset__0(
          &mut *(target as *mut Option<NonNull<T>> as *mut *const Data),
        )
      },
      (target, source) => unsafe {
        v8__Global__Reset__2(
          &mut *(target as *mut Option<NonNull<T>> as *mut *const Data),
          scope,
          &*(source as *const Option<NonNull<T>> as *const *const Data),
        )
      },
    }
    self.isolate_handle = other_value.map(|_| scope.thread_safe_handle());
  }

  /// If non-empty, destroy the underlying storage cell
  /// IsEmpty() will return true after this call.
  pub fn reset(&mut self, scope: &mut Isolate) {
    self.set(scope, None);
  }

  fn check_isolate(&self, isolate: &mut Isolate) {
    match self.value {
      None => assert!(self.isolate_handle.is_none()),
      Some(_) => assert_eq!(
        unsafe { self.isolate_handle.as_ref().unwrap().get_isolate_ptr() },
        isolate as *mut _
      ),
    }
  }
}

impl<T> Default for Global<T> {
  fn default() -> Self {
    Self::new()
  }
}

impl<T> Drop for Global<T> {
  fn drop(&mut self) {
    match &mut self.value {
      None => {
        // This global handle is empty.
        assert!(self.isolate_handle.is_none())
      }
      Some(_)
        if unsafe {
          self
            .isolate_handle
            .as_ref()
            .unwrap()
            .get_isolate_ptr()
            .is_null()
        } =>
      {
        // This global handle is associated with an Isolate that has already
        // been disposed.
      }
      addr @ Some(_) => unsafe {
        // Destroy the storage cell that contains the contents of this Global.
        v8__Global__Reset__0(
          &mut *(addr as *mut Option<NonNull<T>> as *mut *const Data),
        )
      },
    }
  }
}

pub trait AnyHandle<T> {
  fn read(self, isolate: &mut Isolate) -> Option<NonNull<T>>;
}

impl<'s, T> AnyHandle<T> for Local<'s, T> {
  fn read(self, _isolate: &mut Isolate) -> Option<NonNull<T>> {
    Some(self.as_non_null())
  }
}

impl<'s, T> AnyHandle<T> for Option<Local<'s, T>> {
  fn read(self, _isolate: &mut Isolate) -> Option<NonNull<T>> {
    self.map(|local| local.as_non_null())
  }
}

impl<'s, T> AnyHandle<T> for &Global<T> {
  fn read(self, isolate: &mut Isolate) -> Option<NonNull<T>> {
    self.check_isolate(isolate);
    self.value
  }
}