pub unsafe trait JsLifetime<'js> {
type Changed<'to>: 'to;
}
Expand description
The trait which signifies a type using the rquickjs 'js
lifetime trick for maintaining safety around Javascript values.
§Safety
This trait can only be implemented for types which derive a 'js
lifetime from a Javascript
value, directly or indirectly.
All of the base Javascript types used in rquickjs like Value
have a 'js
lifetime. If a
type wants to contains one of those types it must define a lifetime generic. This trait is for
indicating that that lifetime is one derived from a Javascript value. Rquickjs needs to know
about this lifetime so that it is able to ensure safe use of types.
This trait can be derived with #[derive(JsLifetime)]
in most cases, however sometimes a manual
implementation is required.
This trait must be implemented correctly, failing to do so will make it possible to create
unsound behavior. Correct implementions have the 'js
lifetime in JsLifetime<'js>
be the
same as the lifetime on the container, furthermore the associated type Changed<'to>
is
defined as the exact same type with the only difference being that the 'js
lifetime is now
'to
.
The following is a correct implementation of the JsLifetime
trait.
struct Container<'js>(rquickjs::Object<'js>);
unsafe impl<'js> JsLifetime<'js> for Container<'js>{
type Changed<'to> = Container<'to>;
}
If a type does not have any lifetimes associated with it or all the lifetimes are 'static
then if is always save to implement JsLifetime
.
See correct example for a static type below.
struct Bytes(Vec<u8>);
unsafe impl<'js> JsLifetime<'js> for Bytes{
type Changed<'to> = Bytes;
}
§Incorrect examples
For example the following is unsound!
struct Container<'js>(rquickjs::Object<'js>);
unsafe impl<'a,'js> JsLifetime<'js> for Container<'a>{ // WRONG LIFETIME!
type Changed<'to> = Container<'to>;
}
Container
here is defined as having a 'a
lifetime where it should be 'js
.
The following is also incorrect
// Her 'a is not derived from an Javascript value type, but instead the lifetime of a reference.
struct Container<'a,'js>(&'a rquickjs::Object<'js>);
// Non 'js lifetime marked as a 'js lifetime. Unsound!
unsafe impl<'js> JsLifetime<'js> for Container<'js, 'js>{
type Changed<'to> = Container<'to,'to>;
}
The lifetime marked must be from an rquickjs type with a defined <'js>
lifetime, it cannot be a
the lifetime of reference!
Required Associated Types§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.