torrust_tracker_contrib_bencode/cow.rs
1use std::borrow::Cow;
2
3/// Trait for macros to convert owned/borrowed types to `Cow`.
4///
5/// This is needed because `&str` and `String` do not have `From`
6/// implements into `Cow<_, [u8]>`. One solution is to just call `AsRef<[u8]>`
7/// before converting. However, then when a user specifies an owned type,
8/// we will implicitly borrow that; this trait prevents that so that macro
9/// behavior is intuitive, so that owned types stay owned.
10pub trait BCowConvert<'a> {
11 fn convert(self) -> Cow<'a, [u8]>;
12}
13
14// TODO: Enable when specialization lands.
15/*
16impl<'a, T> BCowConvert<'a> for T where T: AsRef<[u8]> + 'a {
17 fn convert(self) -> Cow<'a, [u8]> {
18 self.into()
19 }
20}*/
21
22impl<'a> BCowConvert<'a> for &'a [u8] {
23 fn convert(self) -> Cow<'a, [u8]> {
24 self.into()
25 }
26}
27
28impl<'a> BCowConvert<'a> for &'a str {
29 fn convert(self) -> Cow<'a, [u8]> {
30 self.as_bytes().into()
31 }
32}
33
34impl BCowConvert<'static> for String {
35 fn convert(self) -> Cow<'static, [u8]> {
36 self.into_bytes().into()
37 }
38}
39
40impl BCowConvert<'static> for Vec<u8> {
41 fn convert(self) -> Cow<'static, [u8]> {
42 self.into()
43 }
44}