gccjit/
object.rs

1use context::Context;
2use std::marker::PhantomData;
3use std::fmt;
4use std::ffi::CStr;
5use std::str;
6
7use crate::{context, with_lib};
8
9/// Object represents the root of all objects in gccjit. It is not useful
10/// in and of itself, but it provides the implementation for Debug
11/// used by most objects in this library.
12#[derive(Copy, Clone)]
13pub struct Object<'ctx> {
14    marker: PhantomData<&'ctx Context<'ctx>>,
15    ptr: *mut gccjit_sys::gcc_jit_object
16}
17
18impl<'ctx> fmt::Debug for Object<'ctx> {
19    fn fmt<'a>(&self, fmt: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {
20        let rust_str =
21            with_lib(|lib| {
22                unsafe {
23                    let ptr = lib.gcc_jit_object_get_debug_string(self.ptr);
24                    let cstr = CStr::from_ptr(ptr);
25                    str::from_utf8_unchecked(cstr.to_bytes())
26                }
27            });
28        fmt.write_str(rust_str)
29    }
30}
31
32use std::mem::ManuallyDrop;
33use std::ops::Deref;
34
35#[derive(Debug)]
36pub struct ContextRef<'ctx> {
37    context: ManuallyDrop<Context<'ctx>>,
38}
39
40impl<'ctx> Deref for ContextRef<'ctx> {
41    type Target = Context<'ctx>;
42
43    fn deref(&self) -> &Self::Target {
44        &self.context
45    }
46}
47
48impl<'ctx> Object<'ctx> {
49    pub fn get_context(&self) -> ContextRef<'ctx> {
50        with_lib(|lib| {
51            unsafe {
52                ContextRef {
53                    context: ManuallyDrop::new(context::from_ptr(lib.gcc_jit_object_get_context(self.ptr))),
54                }
55            }
56        })
57    }
58}
59
60/// ToObject is a trait implemented by types that can be upcast to Object.
61pub trait ToObject<'ctx> {
62    fn to_object(&self) -> Object<'ctx>;
63}
64
65impl<'ctx> ToObject<'ctx> for Object<'ctx> {
66    fn to_object(&self) -> Object<'ctx> {
67        unsafe { from_ptr(self.ptr) }
68    }
69}
70
71pub unsafe fn from_ptr<'ctx>(ptr: *mut gccjit_sys::gcc_jit_object) -> Object<'ctx> {
72    Object {
73        marker: PhantomData,
74        ptr
75    }
76}
77
78pub unsafe fn get_ptr<'ctx>(object: &Object<'ctx>) -> *mut gccjit_sys::gcc_jit_object {
79    object.ptr
80}
81
82