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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*!
Utility functions.
*/

use std::{
    cmp::Ord,
    fmt::{self,Debug,Display},
    mem::{self,ManuallyDrop},
    ptr::NonNull,
};


use core_extensions::{
    strings::LeftPadder,
    prelude::*,
};

use crate::std_types::{RString,RStr};


//////////////////////////////////////


/// Information about a panic,used in `ffi_panic_message`. 
#[derive(Debug,Copy,Clone)]
pub struct PanicInfo{
    pub file:&'static str,
    pub line:u32,
}


/// Prints an error message for attempting to panic across the 
/// ffi boundary and aborts the process.
#[inline(never)]
#[cold]
pub fn ffi_panic_message(info:&'static PanicInfo) -> ! {
    eprintln!("\nfile:{}\nline:{}", info.file, info.line);
    eprintln!("Attempted to panic across the ffi boundary.");
    eprintln!("Aborting to handle the panic...\n");
    std::process::exit(1);
}

//////////////////////////////////


/// Coverts a `&T` to a `NonNull<T>`. 
/// 
/// # Eaxmple
/// 
/// ```rust
/// use abi_stable::utils::ref_as_nonnull;
///
/// use std::ptr::NonNull;
/// 
/// const NUMBER: NonNull<u64> = ref_as_nonnull(&100);
/// 
/// ```
pub const fn ref_as_nonnull<T>(reference: &T) -> NonNull<T> {
    unsafe{
        NonNull::new_unchecked(reference as *const T as *mut T)
    }
}


//////////////////////////////////


#[doc(hidden)]
pub struct AbortBomb{
    pub fuse:&'static PanicInfo,
}

impl Drop for AbortBomb{
    fn drop(&mut self){
        ffi_panic_message(self.fuse);
    }
}


//////////////////////////////////

/// Helper type for transmuting between `Copy` types
/// without adding any overhead in debug builds.
/// 
/// # Safety
/// 
/// Be aware that using this type is equivalent to using [`std::mem::transmute_copy`],
/// which doesn't check that `T` and `U` have the same size.
///
/// [`std::mem::transmute_copy`]: https://doc.rust-lang.org/std/mem/fn.transmute_copy.html
#[repr(C)]
pub union Transmuter<T: Copy, U: Copy> {
    pub from: T,
    pub to: U,
}

//////////////////////////////////

/// Leaks `value` into the heap,and returns a reference to it.
/// 
/// # Warning
/// 
/// You must be careful when calling this function,
/// since this leak is ignored by [miri](https://github.com/rust-lang/miri).
/// 
#[inline]
pub fn leak_value<'a,T>(value:T)->&'a T
where T:'a // T:'a is for the docs
{
    let x = Box::new(value);
    let leaked: &'a T = Box::leak(x);
    #[cfg(miri)]
    unsafe{
        crate::miri_static_root(leaked as *const T as *const u8);
    }
    leaked
}


/// Transmute a reference to another reference,
/// changing the referent's type.
/// 
/// # Safety
///
/// This has the same safety concerns that `std::mem::transmute` has,including that
/// `T` has to have an alignment and be compatible with `U`.
#[inline]
#[allow(clippy::needless_lifetimes)]
pub unsafe fn transmute_reference<T,U>(ref_:&T)->&U{
    &*(ref_ as *const _ as *const U)
}


/// Transmute a mutable reference to another mutable reference,
/// changing the referent's type.
/// 
/// # Safety
///
/// This has the same safety concerns that `std::mem::transmute` has,including that
/// `T` has to have an alignment and be compatible with `U`.
#[inline]
#[allow(clippy::needless_lifetimes)]
pub unsafe fn transmute_mut_reference<'a,T,U>(ref_:&'a mut T)->&'a mut U{
    &mut *(ref_ as *mut _ as *mut U)
}

//////////////////////////////////////


#[allow(dead_code)]
pub(crate) fn min_by<T,F,K>(l:T,r:T,mut f:F)->T
where 
    F:FnMut(&T)->K,
    K:Ord,
{
    if f(&l) < f(&r) {
        l
    }else{
        r
    }
}


#[allow(dead_code)]
pub(crate) fn max_by<T,F,K>(l:T,r:T,mut f:F)->T
where 
    F:FnMut(&T)->K,
    K:Ord,
{
    if f(&l) > f(&r) {
        l
    }else{
        r
    }
}

#[doc(hidden)]
pub fn min_max_by<T,F,K>(l:T,r:T,mut f:F)->(T,T)
where 
    F:FnMut(&T)->K,
    K:Ord,
{
    if f(&l) < f(&r) {
        (l,r)
    }else{
        (r,l)
    }
}



//////////////////////////////////////




pub(crate) trait FmtPadding{
    fn display_pad<'a,T>(&'a mut self,padding:usize,v:&T)->Result<LeftPadder<'a> ,fmt::Error>
    where T:Display;

    fn debug_pad<'a,T>(&'a mut self,padding:usize,v:&T)->Result<LeftPadder<'a> ,fmt::Error>
    where T:Debug;
}


macro_rules! impl_fmt_padding {
    ($ty:ty) => (
        impl FmtPadding for $ty{
            fn display_pad<'a,T>(
                &'a mut self,
                padding:usize,
                v:&T
            )->Result<LeftPadder<'a> ,fmt::Error>
            where T:Display
            {
                use std::fmt::Write;
                let this=self.into_type_mut();

                this.clear();

                writeln!(this,"{}",v)?;

                Ok(this.left_padder(padding))
            }

            fn debug_pad<'a,T>(
                &'a mut self,
                padding:usize,
                v:&T
            )->Result<LeftPadder<'a> ,fmt::Error>
            where T:Debug
            {
                use std::fmt::Write;
                let this=self.into_type_mut();

                this.clear();

                writeln!(this,"{:#?}",v)?;

                Ok(this.left_padder(padding))
            }           
        }

    )
 }





impl_fmt_padding!{ String }
impl_fmt_padding!{ RString }




//////////////////////////////////////////////////////////////////////

/// Takes the contents out of a `ManuallyDrop<T>`.
///
/// # Safety
///
/// After this function is called `slot` will become uninitialized and 
/// must not be read again.
pub unsafe fn take_manuallydrop<T>(slot: &mut ManuallyDrop<T>) -> T {
    #[cfg(feature = "rust_1_42")]
    {
        ManuallyDrop::take(slot)
    }
    #[cfg(not(feature = "rust_1_42"))]
    {
        ManuallyDrop::into_inner(std::ptr::read(slot))
    }
}


#[doc(hidden)]
#[inline(always)]
pub fn assert_fnonce<F,R>(_:&F)
where
    F:FnOnce()->R
{}


/// This function allows calculating the distance (in `T`s) from `from` to `to`.
/// 
/// This returns `None` if `from` has a higher address than `to`,
/// or if `T` is a zero sized type.
/// 
/// # Example
/// 
/// ```
/// use abi_stable::utils;
/// 
/// let arr=["hello","world","foo","bar","baz"];
/// 
/// assert_eq!(utils::distance_from(&arr[0],&arr[0]),Some(0));
/// assert_eq!(utils::distance_from(&arr[0],&arr[4]),Some(4));
///
/// assert_eq!(utils::distance_from(&arr[4],&arr[0]),None);
/// 
/// ```
pub fn distance_from<T>(from:*const T,to:*const T)->Option<usize>{
    (to as usize)
        .checked_sub(from as usize)?
        .checked_div(mem::size_of::<T>())
}


//////////////////////////////////////////////////////////////////////

#[doc(hidden)]
pub extern "C" fn get_type_name<T>()->RStr<'static>{
    RStr::from(std::any::type_name::<T>())
}


#[cfg(test)]
mod tests{
    use super::*;

    #[test]
    fn distance_from_(){
        let int_array=[0,1,2,3,4];
        let unit_array=[(),(),(),(),()];

        for (ix,x) in int_array.iter().enumerate() {
            for (iy,y) in int_array.iter().enumerate() {
                if ix <= iy {
                    assert_eq!(distance_from(x,y), Some(iy-ix));
                }else{
                    assert_eq!(distance_from(x,y), None);
                }
            }
        }

        for x in &unit_array {
            for y in &unit_array {
                assert_eq!(distance_from(x,y), None);
            }
        }

    }
}