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
#![doc(html_root_url = "https://docs.rs/toad-writable/0.0.0")]
#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
#![allow(clippy::unused_unit)]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(missing_copy_implementations)]
#![cfg_attr(not(test), deny(unsafe_code))]
#![cfg_attr(not(test), warn(unreachable_pub))]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;
use core::fmt::Display;
use core::ops::{Deref, DerefMut};
use toad_array::Array;
#[derive(Clone, Copy, Debug, Default)]
pub struct Writable<A: Array<Item = u8>>(A);
impl<A: Array<Item = u8>> Writable<A> {
pub fn as_str(&self) -> &str {
core::str::from_utf8(self).unwrap()
}
pub fn as_slice(&self) -> &[u8] {
&self.0
}
pub fn as_mut_slice(&mut self) -> &mut [u8] {
&mut self.0
}
pub fn unwrap(self) -> A {
self.0
}
}
impl<A> Display for Writable<A> where A: Array<Item = u8>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl<A: Array<Item = u8>> From<A> for Writable<A> {
fn from(a: A) -> Self {
Self(a)
}
}
impl<A: Array<Item = u8>> Deref for Writable<A> {
type Target = A;
fn deref(&self) -> &A {
&self.0
}
}
impl<A: Array<Item = u8>> DerefMut for Writable<A> {
fn deref_mut(&mut self) -> &mut A {
&mut self.0
}
}
impl<A: Array<Item = u8>> AsRef<str> for Writable<A> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<A: Array<Item = u8>> core::fmt::Write for Writable<A> {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
match A::CAPACITY {
| Some(max) if max < self.len() + s.len() => Err(core::fmt::Error),
| _ => {
self.extend(s.bytes());
Ok(())
},
}
}
}