swift_runtime/
metadata.rs1use core::ffi::c_void;
4use swift_runtime_sys::SwiftABI::*;
5
6#[derive(Clone, Copy)]
8pub struct Metadata(*const c_void);
9
10impl Metadata {
11 pub fn from_raw(ptr: *const c_void) -> Option<Self> {
13 if ptr.is_null() {
14 None
15 } else {
16 Some(Self(ptr))
17 }
18 }
19
20 pub fn as_raw(&self) -> *const c_void {
22 self.0
23 }
24
25 pub fn kind(&self) -> MetadataKind {
27 let raw = unsafe { *(self.0 as *const usize) };
28 get_enumerated_metadata_kind(raw)
29 }
30
31 pub fn value_witness_table(&self) -> &ValueWitnessTable {
33 unsafe { &*get_value_witness_table(self.0) }
34 }
35
36 pub fn size(&self) -> usize {
38 self.value_witness_table().get_size()
39 }
40
41 pub fn stride(&self) -> usize {
43 self.value_witness_table().get_stride()
44 }
45
46 pub fn alignment(&self) -> usize {
48 self.value_witness_table().get_alignment()
49 }
50
51 pub fn is_pod(&self) -> bool {
53 self.value_witness_table().is_pod()
54 }
55
56 pub fn type_name(&self, qualified: bool) -> Option<String> {
58 let result =
59 unsafe { swift_runtime_sys::SwiftCCThunks::swift_getTypeName(self.0, qualified) };
60 match result {
61 Ok((name, len)) if len > 0 => Some(name.to_string()),
62 _ => None,
63 }
64 }
65
66 pub fn descriptor(&self) -> Option<*const c_void> {
68 let result =
69 unsafe { swift_runtime_sys::SwiftCCThunks::swift_getTypeContextDescriptor(self.0) };
70 match result {
71 Ok(ptr) if !ptr.is_null() => Some(ptr),
72 _ => None,
73 }
74 }
75
76 pub fn descriptor_name(&self) -> Option<String> {
78 let desc = self.descriptor()?;
79 let tcd = unsafe { &*(desc as *const TypeContextDescriptor) };
80 let name = unsafe { tcd.get_name() };
81 name.to_str().ok().map(|s| s.to_string())
82 }
83}
84
85impl std::fmt::Debug for Metadata {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 let name = self
88 .type_name(true)
89 .unwrap_or_else(|| format!("{:?}", self.0));
90 write!(
91 f,
92 "Metadata({}, kind={:?}, size={})",
93 name,
94 self.kind(),
95 self.size()
96 )
97 }
98}
99
100pub fn lookup_type(mangled: &[u8]) -> Option<Metadata> {
102 let ptr = unsafe {
103 swift_runtime_sys::RuntimeRaw::swift_getTypeByMangledNameInEnvironment(
104 mangled.as_ptr(),
105 mangled.len(),
106 core::ptr::null(),
107 0,
108 )
109 };
110 Metadata::from_raw(ptr)
111}