1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! Helper methods to determine whether a type is `TraitObject`, `Slice` or `Concrete`, and work with them respectively.
//!
//! # Examples
//!
//! ```
//! # use std::{any};
//! # use metatype::*;
//! assert_eq!(usize::METATYPE, MetaType::Concrete);
//! assert_eq!(any::Any::METATYPE, MetaType::TraitObject);
//! assert_eq!(<[u8]>::METATYPE, MetaType::Slice);
//!
//! let a: Box<usize> = Box::new(123);
//! assert_eq!((&*a).meta_type(), MetaType::Concrete);
//! let a: Box<any::Any> = a;
//! assert_eq!((&*a).meta_type(), MetaType::TraitObject);
//!
//! let a = [123,456];
//! assert_eq!(a.meta_type(), MetaType::Concrete);
//! let a: &[i32] = &a;
//! assert_eq!(a.meta_type(), MetaType::Slice);
//!
//! let a: Box<any::Any> = Box::new(123);
//! // https://github.com/rust-lang/rust/issues/50318
//! // let meta: TraitObject = (&*a).meta();
//! // println!("vtable: {:?}", meta.vtable);
//! ```
//!
//! # Note
//!
//! This currently requires Rust nightly for the `raw` and `specialization` features.

#![doc(html_root_url = "https://docs.rs/metatype/0.1.1")]
#![feature(raw, box_syntax, specialization)]
#![deny(missing_docs, warnings, deprecated)]

use std::{any, mem, raw};

/// Implemented on all types, it provides helper methods to determine whether a type is `TraitObject`, `Slice` or `Concrete`, and work with them respectively.
pub trait Type {
	/// Enum describing whether a type is `TraitObject`, `Slice` or `Concrete`.
	const METATYPE: MetaType;
	/// Type of metadata for type.
	type Meta: 'static;
	/// Helper method describing whether a type is `TraitObject`, `Slice` or `Concrete`.
	fn meta_type(&self) -> MetaType {
		Self::METATYPE
	}
	/// Retrieve [TraitObject], [Slice] or [Concrete] meta data respectively for a type
	fn meta(&self) -> Self::Meta;
	/// Retrieve pointer to the data
	fn data(&self) -> *const ();
	/// Retrieve mut pointer to the data
	fn data_mut(&mut self) -> *mut ();
	/// Create a `Box<Self>` with the provided `Self::Meta` but with the allocated data uninitialized.
	unsafe fn uninitialized_box(Self::Meta) -> Box<Self>;
}
/// Meta type of a type
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum MetaType {
	/// Trait object, thus unsized
	TraitObject,
	/// Slice, thus unsized
	Slice,
	/// Sized type
	Concrete,
}

/// Meta data for a trait object
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct TraitObject {
	/// Address of vtable
	pub vtable: &'static (),
}
/// Meta data for a slice
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Slice {
	/// Number of elements in the slice
	pub len: usize,
}
/// Meta data for a concrete, sized type
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Concrete;

impl<T: ?Sized> Type for T {
	#[doc(hidden)]
	default const METATYPE: MetaType = MetaType::TraitObject;
	#[doc(hidden)]
	default type Meta = TraitObject;
	#[inline]
	default fn meta(&self) -> Self::Meta {
		assert_eq!(
			(mem::size_of::<&Self>(), mem::align_of::<&Self>()),
			(
				mem::size_of::<raw::TraitObject>(),
				mem::align_of::<raw::TraitObject>()
			)
		);
		let trait_object: raw::TraitObject = unsafe { mem::transmute_copy(&self) };
		assert_eq!(
			trait_object.data as *const (),
			self as *const T as *const ()
		);
		let ret = TraitObject {
			vtable: unsafe { &*trait_object.vtable },
		};
		assert_eq!(
			any::TypeId::of::<Self::Meta>(),
			any::TypeId::of::<TraitObject>()
		);
		unsafe { mem::transmute_copy(&ret) }
	}
	#[inline]
	default fn data(&self) -> *const () {
		assert_eq!(
			(mem::size_of::<&Self>(), mem::align_of::<&Self>()),
			(
				mem::size_of::<raw::TraitObject>(),
				mem::align_of::<raw::TraitObject>()
			)
		);
		let trait_object: raw::TraitObject = unsafe { mem::transmute_copy(&self) };
		assert_eq!(
			trait_object.data as *const (),
			self as *const T as *const ()
		);
		self as *const T as *const ()
	}
	#[inline]
	default fn data_mut(&mut self) -> *mut () {
		assert_eq!(
			(mem::size_of::<&Self>(), mem::align_of::<&Self>()),
			(
				mem::size_of::<raw::TraitObject>(),
				mem::align_of::<raw::TraitObject>()
			)
		);
		let trait_object: raw::TraitObject = unsafe { mem::transmute_copy(&self) };
		assert_eq!(trait_object.data, self as *mut T as *mut ());
		self as *mut T as *mut ()
	}
	default unsafe fn uninitialized_box(t: Self::Meta) -> Box<Self> {
		assert_eq!(
			any::TypeId::of::<Self::Meta>(),
			any::TypeId::of::<TraitObject>()
		);
		let t: TraitObject = mem::transmute_copy(&t);
		assert_eq!(
			(mem::size_of::<&Self>(), mem::align_of::<&Self>()),
			(
				mem::size_of::<raw::TraitObject>(),
				mem::align_of::<raw::TraitObject>()
			)
		);
		let object: &Self = mem::transmute_copy(&raw::TraitObject {
			data: &mut (),
			vtable: t.vtable as *const () as *mut (),
		}); // ptr::null_mut() causes llvm to assume below is unreachable
		let (size, align) = (mem::size_of_val(object), mem::align_of_val(object));
		let mut backing = Vec::with_capacity(size);
		backing.set_len(size);
		let backing: Box<[u8]> = backing.into_boxed_slice();
		assert_eq!(backing.get_unchecked(0) as *const u8 as usize % align, 0);
		let backing = mem::transmute::<_, raw::TraitObject>(backing); // TODO: work out how to make backing sufficiently aligned
		assert_eq!(
			(mem::size_of::<Box<Self>>(), mem::align_of::<Box<Self>>()),
			(
				mem::size_of::<raw::TraitObject>(),
				mem::align_of::<raw::TraitObject>()
			)
		);
		mem::transmute_copy(&raw::TraitObject {
			data: backing.data,
			vtable: t.vtable as *const () as *mut (),
		})
	}
}
#[doc(hidden)]
impl<T: Sized> Type for T {
	const METATYPE: MetaType = MetaType::Concrete;
	type Meta = Concrete;
	#[inline]
	fn meta(&self) -> Self::Meta {
		Concrete
	}
	#[inline]
	fn data(&self) -> *const () {
		self as *const Self as *const ()
	}
	#[inline]
	fn data_mut(&mut self) -> *mut () {
		self as *mut Self as *mut ()
	}
	unsafe fn uninitialized_box(_: Self::Meta) -> Box<Self> {
		box mem::uninitialized()
	}
}
#[doc(hidden)]
impl<T: Sized> Type for [T] {
	const METATYPE: MetaType = MetaType::Slice;
	type Meta = Slice;
	#[inline]
	fn meta(&self) -> Self::Meta {
		assert_eq!(
			(mem::size_of_val(self), mem::align_of_val(self)),
			(mem::size_of::<T>() * self.len(), mem::align_of::<T>())
		);
		Slice { len: self.len() }
	}
	#[inline]
	fn data(&self) -> *const () {
		self.as_ptr() as *const ()
	}
	#[inline]
	fn data_mut(&mut self) -> *mut () {
		self.as_mut_ptr() as *mut ()
	}
	unsafe fn uninitialized_box(t: Self::Meta) -> Box<Self> {
		let mut backing = Vec::<T>::with_capacity(t.len);
		backing.set_len(t.len);
		backing.into_boxed_slice()
	}
}
#[doc(hidden)]
impl Type for str {
	const METATYPE: MetaType = MetaType::Slice;
	type Meta = Slice;
	#[inline]
	fn meta(&self) -> Self::Meta {
		assert_eq!(
			(mem::size_of_val(self), mem::align_of_val(self)),
			(self.len(), 1)
		);
		Slice { len: self.len() }
	}
	#[inline]
	fn data(&self) -> *const () {
		self.as_ptr() as *const ()
	}
	#[inline]
	fn data_mut(&mut self) -> *mut () {
		unsafe { self.as_bytes_mut() }.as_mut_ptr() as *mut ()
	}
	unsafe fn uninitialized_box(t: Self::Meta) -> Box<Self> {
		let mut backing = Vec::<u8>::with_capacity(t.len);
		backing.set_len(t.len);
		String::from_utf8_unchecked(backing).into_boxed_str()
	}
}

#[cfg(test)]
mod tests {
	use super::{MetaType, Type};
	use std::{any, mem, ptr};

	#[test]
	fn abc() {
		let a: Box<usize> = Box::new(123);
		assert_eq!(Type::meta_type(&*a), MetaType::Concrete);
		assert_eq!(Type::meta_type(&a), MetaType::Concrete);
		let a: Box<any::Any> = a;
		assert_eq!(Type::meta_type(&*a), MetaType::TraitObject);
		assert_eq!(Type::meta_type(&a), MetaType::Concrete);
		let meta = Type::meta(&*a); // : TraitObject
		let mut b: Box<any::Any> = unsafe { Type::uninitialized_box(meta) };
		assert_eq!(mem::size_of_val(&*b), mem::size_of::<usize>());
		unsafe { ptr::write(&mut *b as *mut any::Any as *mut usize, 456usize) };
		let x: usize = *Box::<any::Any>::downcast(b).unwrap();
		assert_eq!(x, 456);
		let a: &[usize] = &[1, 2, 3];
		assert_eq!(Type::meta_type(a), MetaType::Slice);
		let a: Box<[usize]> = vec![1usize, 2, 3].into_boxed_slice();
		assert_eq!(Type::meta_type(&*a), MetaType::Slice);
		assert_eq!(Type::meta_type(&a), MetaType::Concrete);
		let a: &str = "abc";
		assert_eq!(Type::meta_type(a), MetaType::Slice);
		assert_eq!(Type::meta_type(&a), MetaType::Concrete);
	}
}