Struct Gc

Source
pub struct Gc<'gc, T>
where T: 'gc + ?Sized,
{ /* private fields */ }
Expand description

A garbage collected pointer to a type T. Implements Copy, and is implemented as a plain machine pointer. You can only allocate Gc pointers through a &Mutation<'gc> inside an arena type, and through “generativity” such Gc pointers may not escape the arena they were born in or be stored inside TLS. This, combined with correct Collect implementations, means that Gc pointers will never be dangling and are always safe to access.

Implementations§

Source§

impl<'gc, T> Gc<'gc, T>
where T: Collect + 'gc,

Source

pub fn new(mc: &Mutation<'gc>, t: T) -> Gc<'gc, T>

Examples found in repository?
examples/basic.rs (line 95)
84
85
86
87
88
89
90
91
92
93
94
95
96
97
fn get_running_project(xml: &str, system: Rc<StdSystem<C>>) -> EnvArena {
    EnvArena::new(|mc| {
        let parser = ast::Parser::default();
        let ast = parser.parse(xml).unwrap();
        assert_eq!(ast.roles.len(), 1); // this should be handled more elegantly in practice - for the sake of this example, we only allow one role

        let (bytecode, init_info, locs, _) = ByteCode::compile(&ast.roles[0]).unwrap();

        let mut proj = Project::from_init(mc, &init_info, Rc::new(bytecode), Settings::default(), system);
        proj.input(mc, Input::Start); // this is equivalent to clicking the green flag button

        Env { proj: Gc::new(mc, RefLock::new(proj)), locs }
    })
}
Source§

impl<'gc, T> Gc<'gc, T>
where T: 'gc,

Source

pub unsafe fn cast<U>(this: Gc<'gc, T>) -> Gc<'gc, U>
where U: 'gc,

Cast the internal pointer to a different type.

SAFETY: It must be valid to dereference a *mut U that has come from casting a *mut T.

Source

pub unsafe fn from_ptr(ptr: *const T) -> Gc<'gc, T>

Retrieve a Gc from a raw pointer obtained from Gc::as_ptr

SAFETY: The provided pointer must have been obtained from Gc::as_ptr, and the pointer must not have been collected yet.

Source§

impl<'gc, T> Gc<'gc, T>
where T: Unlock + 'gc + ?Sized,

Source

pub fn unlock(self, mc: &Mutation<'gc>) -> &'gc <T as Unlock>::Unlocked

Shorthand for Gc::write(mc, self).unlock().

Source§

impl<'gc, T> Gc<'gc, T>
where T: 'gc + ?Sized,

Source

pub fn as_ref(self) -> &'gc T

Obtains a long-lived reference to the contents of this Gc.

Unlike AsRef or Deref, the returned reference isn’t bound to the Gc itself, and will stay valid for the entirety of the current arena callback.

Source

pub fn downgrade(this: Gc<'gc, T>) -> GcWeak<'gc, T>

Source

pub fn write(mc: &Mutation<'gc>, gc: Gc<'gc, T>) -> &'gc Write<T>

Triggers a write barrier on this Gc, allowing for further safe mutation.

Source

pub fn ptr_eq(this: Gc<'gc, T>, other: Gc<'gc, T>) -> bool

Returns true if two Gcs point to the same allocation.

Similarly to Rc::ptr_eq and Arc::ptr_eq, this function ignores the metadata of dyn pointers.

Source

pub fn as_ptr(gc: Gc<'gc, T>) -> *const T

Source

pub fn is_dead(_: &Finalization<'gc>, gc: Gc<'gc, T>) -> bool

Returns true when a pointer is dead during finalization. This is equivalent to GcWeak::is_dead for strong pointers.

Any strong pointer reachable from the root will never be dead, BUT there can be strong pointers reachable only through other weak pointers that can be dead.

Source

pub fn resurrect(fc: &Finalization<'gc>, gc: Gc<'gc, T>)

Manually marks a dead Gc pointer as reachable and keeps it alive.

Equivalent to GcWeak::resurrect for strong pointers. Manually marks this pointer and all transitively held pointers as reachable, thus keeping them from being dropped this collection cycle.

Source§

impl<'gc, T> Gc<'gc, Lock<T>>
where T: Copy + 'gc,

Source

pub fn get(self) -> T

Source

pub fn set(self, mc: &Mutation<'gc>, t: T)

Source§

impl<'gc, T> Gc<'gc, RefLock<T>>
where T: 'gc + ?Sized,

Source

pub fn borrow(self) -> Ref<'gc, T>

Source

pub fn try_borrow(self) -> Result<Ref<'gc, T>, BorrowError>

Source

pub fn borrow_mut(self, mc: &Mutation<'gc>) -> RefMut<'gc, T>

Examples found in repository?
examples/basic.rs (line 140)
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
fn main() {
    // read in an xml file whose path is given as a command line argument
    let args = std::env::args().collect::<Vec<_>>();
    if args.len() != 2 {
        panic!("usage: {} [xml file]", &args[0]);
    }
    let mut xml = String::new();
    std::fs::File::open(&args[1]).expect("failed to open file").read_to_string(&mut xml).expect("failed to read file");

    // create a new shared clock and start a thread that updates it at our desired interval
    let clock = Arc::new(Clock::new(UtcOffset::UTC, Some(Precision::Medium)));
    let clock_clone = clock.clone();
    std::thread::spawn(move || loop {
        std::thread::sleep(CLOCK_INTERVAL);
        clock_clone.update();
    });

    // create a custom config for the system - in this simple example we just implement the say/think blocks to print to stdout
    let config = Config::<C, StdSystem<C>> {
        request: None,
        command: Some(Rc::new(|_mc, key, command, _proc| match command {
            Command::Print { style: _, value } => {
                if let Some(value) = value {
                    println!("{value:?}");
                }
                key.complete(Ok(())); // any request that you handle must be completed - otherwise the calling process will hang forever
                CommandStatus::Handled
            }
            _ => CommandStatus::UseDefault { key, command }, // anything you don't handle should return the key and command to invoke the default behavior instead
        })),
    };

    // initialize our system with all the info we've put together
    let system = Rc::new(StdSystem::new_sync(CompactString::new(BASE_URL), None, config, clock.clone()));
    let mut env = get_running_project(&xml, system);

    // begin running the code - these are some helpers to make things more efficient in terms of memory and cpu resources
    let mut idle_sleeper = IdleAction::new(YIELDS_BEFORE_SLEEP, Box::new(|| std::thread::sleep(IDLE_SLEEP_TIME)));
    let mut next_collect = clock.read(Precision::Medium) + COLLECT_INTERVAL;
    loop {
        env.mutate(|mc, env| {
            let mut proj = env.proj.borrow_mut(mc);
            for _ in 0..1024 {
                // step the virtual machine forward by one bytecode instruction
                let res = proj.step(mc);
                if let ProjectStep::Error { error, proc } = &res {
                    // if we get an error, we can generate an error summary including a stack trace - here we just print out the result
                    let trace = ErrorSummary::extract(error, proc, &env.locs);
                    println!("error: {error:?}\ntrace: {trace:?}");
                }
                // this takes care of performing thread sleep if we get a bunch of no-ops from proj.step back to back
                idle_sleeper.consume(&res);
            }
        });
        // if it's time for us to do garbage collection, do it and reset the next collection time
        if clock.read(Precision::Low) >= next_collect {
            env.collect_all();
            next_collect = clock.read(Precision::Medium) + COLLECT_INTERVAL;
        }
    }
}
Source

pub fn try_borrow_mut( self, mc: &Mutation<'gc>, ) -> Result<RefMut<'gc, T>, BorrowMutError>

Trait Implementations§

Source§

impl<'gc, T> AsRef<T> for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<'gc, T> Clone for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

fn clone(&self) -> Gc<'gc, T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'gc, T> Collect for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

fn trace(&self, cc: &Collection)

Must call Collect::trace on all held Gc pointers. If this type holds inner types that implement Collect, a valid implementation would simply call Collect::trace on all the held values to ensure this.
Source§

fn needs_trace() -> bool
where Self: Sized,

As an optimization, if this type can never hold a Gc pointer and trace is unnecessary to call, you may implement this method and return false. The default implementation returns true, signaling that Collect::trace must be called.
Source§

impl<'gc, T> Debug for Gc<'gc, T>
where T: Debug + 'gc + ?Sized,

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'gc, T> Deref for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &T

Dereferences the value.
Source§

impl<'gc, T> Display for Gc<'gc, T>
where T: Display + 'gc + ?Sized,

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'gc, C: CustomTypes<S>, S: System<C>> From<Gc<'gc, RefLock<Closure<'gc, C, S>>>> for Value<'gc, C, S>

Source§

fn from(v: Gc<'gc, RefLock<Closure<'gc, C, S>>>) -> Self

Converts to this type from the input type.
Source§

impl<'gc, C: CustomTypes<S>, S: System<C>> From<Gc<'gc, RefLock<Entity<'gc, C, S>>>> for Value<'gc, C, S>

Source§

fn from(v: Gc<'gc, RefLock<Entity<'gc, C, S>>>) -> Self

Converts to this type from the input type.
Source§

impl<'gc, C: CustomTypes<S>, S: System<C>> From<Gc<'gc, RefLock<VecDeque<Value<'gc, C, S>>>>> for Value<'gc, C, S>

Source§

fn from(v: Gc<'gc, RefLock<VecDeque<Value<'gc, C, S>>>>) -> Self

Converts to this type from the input type.
Source§

impl<'gc, T> Hash for Gc<'gc, T>
where T: Hash + 'gc + ?Sized,

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'gc, T> Ord for Gc<'gc, T>
where T: Ord + 'gc + ?Sized,

Source§

fn cmp(&self, other: &Gc<'gc, T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<'gc, T> PartialEq for Gc<'gc, T>
where T: PartialEq + 'gc + ?Sized,

Source§

fn eq(&self, other: &Gc<'gc, T>) -> bool

Tests for self and other values to be equal, and is used by ==.
Source§

fn ne(&self, other: &Gc<'gc, T>) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'gc, T> PartialOrd for Gc<'gc, T>
where T: PartialOrd + 'gc + ?Sized,

Source§

fn partial_cmp(&self, other: &Gc<'gc, T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn le(&self, other: &Gc<'gc, T>) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
Source§

fn lt(&self, other: &Gc<'gc, T>) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn ge(&self, other: &Gc<'gc, T>) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

fn gt(&self, other: &Gc<'gc, T>) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
Source§

impl<'gc, T> Pointer for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'gc, T> Copy for Gc<'gc, T>
where T: 'gc + ?Sized,

Source§

impl<'gc, T> Eq for Gc<'gc, T>
where T: Eq + 'gc + ?Sized,

Auto Trait Implementations§

§

impl<'gc, T> Freeze for Gc<'gc, T>
where T: ?Sized,

§

impl<'gc, T> !RefUnwindSafe for Gc<'gc, T>

§

impl<'gc, T> !Send for Gc<'gc, T>

§

impl<'gc, T> !Sync for Gc<'gc, T>

§

impl<'gc, T> Unpin for Gc<'gc, T>
where T: ?Sized,

§

impl<'gc, T> !UnwindSafe for Gc<'gc, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToCompactString for T
where T: Display,

Source§

fn to_compact_string(&self) -> CompactString

Converts the given value to a CompactString. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,