1use super::*;
2
3pub struct Data {
5 ptr: *mut u8,
6 len: usize,
7}
8
9impl Data {
10 pub fn new(len: usize) -> Self {
12 unsafe {
13 let bytes = Self::alloc(len);
14
15 if len > 0 {
16 core::ptr::write_bytes(bytes.ptr, 0, len);
17 }
18
19 bytes
20 }
21 }
22
23 pub fn as_wide(&self) -> &[u16] {
25 if self.ptr.is_null() {
26 &[]
27 } else {
28 unsafe { core::slice::from_raw_parts(self.ptr as *const u16, self.len / 2) }
29 }
30 }
31
32 pub fn from_slice(slice: &[u8]) -> Self {
34 unsafe {
35 let bytes = Self::alloc(slice.len());
36
37 if !slice.is_empty() {
38 core::ptr::copy_nonoverlapping(slice.as_ptr(), bytes.ptr, slice.len());
39 }
40
41 bytes
42 }
43 }
44
45 unsafe fn alloc(len: usize) -> Self {
47 if len == 0 {
48 Self {
49 ptr: null_mut(),
50 len: 0,
51 }
52 } else {
53 let ptr = unsafe { HeapAlloc(GetProcessHeap(), 0, len) as *mut u8 };
55
56 if ptr.is_null() {
57 panic!("allocation failed");
58 }
59
60 Self { ptr, len }
61 }
62 }
63}
64
65impl Drop for Data {
66 fn drop(&mut self) {
67 if !self.ptr.is_null() {
68 unsafe {
69 HeapFree(GetProcessHeap(), 0, self.ptr as *mut _);
70 }
71 }
72 }
73}
74
75impl Deref for Data {
76 type Target = [u8];
77
78 fn deref(&self) -> &[u8] {
79 if self.ptr.is_null() {
80 &[]
81 } else {
82 unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
83 }
84 }
85}
86
87impl core::ops::DerefMut for Data {
88 fn deref_mut(&mut self) -> &mut [u8] {
89 if self.ptr.is_null() {
90 &mut []
91 } else {
92 unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
93 }
94 }
95}
96
97impl Clone for Data {
98 fn clone(&self) -> Self {
99 Self::from_slice(self)
100 }
101}
102
103impl PartialEq for Data {
104 fn eq(&self, other: &Self) -> bool {
105 self.deref() == other.deref()
106 }
107}
108
109impl Eq for Data {}
110
111impl core::fmt::Debug for Data {
112 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
113 self.deref().fmt(f)
114 }
115}
116
117impl<const N: usize> From<[u8; N]> for Data {
118 fn from(from: [u8; N]) -> Self {
119 Self::from_slice(&from)
120 }
121}