cfn_guard/rules/libyaml/
util.rs1use std::{
2 marker::PhantomData,
3 mem::{self, MaybeUninit},
4 ops::Deref,
5 ptr::{addr_of, NonNull},
6};
7
8use crate::rules::path_value::Location;
9#[allow(clippy::unsafe_removed_from_name)]
10use unsafe_libyaml as sys;
11
12pub(crate) struct Owned<T, Init = T> {
13 ptr: NonNull<T>,
14 marker: PhantomData<NonNull<Init>>,
15}
16
17impl<T> Owned<T> {
18 pub fn new_uninit() -> Owned<MaybeUninit<T>, T> {
19 let boxed = Box::new(MaybeUninit::<T>::uninit());
21 Owned {
22 ptr: unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) },
23 marker: PhantomData,
24 }
25 }
26
27 pub unsafe fn assume_init(definitely_init: Owned<MaybeUninit<T>, T>) -> Owned<T> {
28 let ptr = definitely_init.ptr;
29 mem::forget(definitely_init);
30 Owned {
31 ptr: ptr.cast(),
32 marker: PhantomData,
33 }
34 }
35}
36
37#[repr(transparent)]
38pub(crate) struct InitPtr<T> {
39 pub ptr: *mut T,
40}
41
42impl<T, Init> Deref for Owned<T, Init> {
43 type Target = InitPtr<Init>;
44
45 fn deref(&self) -> &Self::Target {
46 unsafe { &*addr_of!(self.ptr).cast::<InitPtr<Init>>() }
47 }
48}
49
50impl<T, Init> Drop for Owned<T, Init> {
51 fn drop(&mut self) {
52 let _ = unsafe { Box::from_raw(self.ptr.as_ptr()) };
53 }
54}
55
56pub(crate) fn system_mark_to_location(mark: sys::yaml_mark_t) -> Location {
57 Location {
58 line: mark.line as usize,
59 col: mark.column as usize,
60 }
61}