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
#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(clippy))]

use std::borrow::Borrow;


/// Allows creating a default static reference to a type.
pub trait DefaultRef: 'static {
    /// Creates a reasonable default static reference for this type.
    fn default_ref() -> &'static Self;
}
impl<T: 'static + ?Sized> DefaultRef for T
    where &'static T: Default
{
    fn default_ref() -> &'static Self {
        Default::default()
    }
}

/// Allows creating a default box of a type.
pub trait DefaultBox: DefaultRef {
    /// Creates a reasonable default box of this type.
    fn default_box() -> Box<Self>;
}
impl<T: DefaultRef + ?Sized> DefaultBox for T
    where Box<T>: Default
{
    fn default_box() -> Box<Self> {
        Default::default()
    }
}

/// Allows creating a default owned version of a type.
pub trait DefaultOwned: DefaultBox + ToOwned {
    /// Creates a reasonable, owned default of this type.
    fn default_owned() -> <Self as ToOwned>::Owned;
}
impl<O: Default + Borrow<T>, T: DefaultBox + ToOwned<Owned=O> + ?Sized> DefaultOwned for T {
    fn default_owned() -> <Self as ToOwned>::Owned {
        Default::default()
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::{CStr, CString, OsStr, OsString};
    //use std::path::{Path, PathBuf};

    use super::{DefaultRef, DefaultBox, DefaultOwned};

    #[test]
    fn string() {
        let _: &str = str::default_ref();
        let _: Box<str> = str::default_box();
        let _: String = str::default_owned();
    }

    #[test]
    fn bytes() {
        let _: &[u8] = <[u8]>::default_ref();
        let _: Box<[u8]> = <[u8]>::default_box();
        let _: Vec<u8> = <[u8]>::default_owned();
    }

    #[test]
    fn floats() {
        let _: &[f64] = <[f64]>::default_ref();
        let _: Box<[f64]> = <[f64]>::default_box();
        let _: Vec<f64> = <[f64]>::default_owned();
    }

    #[test]
    fn c_string() {
        let _: &CStr = CStr::default_ref();
        let _: Box<CStr> = CStr::default_box();
        let _: CString = CStr::default_owned();
    }

    #[test]
    fn os_string() {
        let _: &OsStr = OsStr::default_ref();
        let _: Box<OsStr> = OsStr::default_box();
        let _: OsString = OsStr::default_owned();
    }

    //#[test]
    //fn path_buf() {
    //    let _: &Path = Path::default_ref();
    //    let _: Box<Path> = Path::default_box();
    //    let _: PathBuf = Path::default_owned();
    //}
}