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;
pub trait DefaultRef: 'static {
fn default_ref() -> &'static Self;
}
impl<T: 'static + ?Sized> DefaultRef for T
where &'static T: Default
{
fn default_ref() -> &'static Self {
Default::default()
}
}
pub trait DefaultBox: DefaultRef {
fn default_box() -> Box<Self>;
}
impl<T: DefaultRef + ?Sized> DefaultBox for T
where Box<T>: Default
{
fn default_box() -> Box<Self> {
Default::default()
}
}
pub trait DefaultOwned: DefaultBox + ToOwned {
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 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();
}
}