@@ -176,6 +176,22 @@ impl From<&QByteArray> for Vec<u8> {
176
176
}
177
177
}
178
178
179
+ #[ cfg( feature = "bytes" ) ]
180
+ impl From < & bytes:: Bytes > for QByteArray {
181
+ /// Convert `bytes::Bytes` to a QByteArray. This makes a deep copy of the data.
182
+ fn from ( value : & bytes:: Bytes ) -> Self {
183
+ Self :: from ( value. as_ref ( ) )
184
+ }
185
+ }
186
+
187
+ #[ cfg( feature = "bytes" ) ]
188
+ impl From < & QByteArray > for bytes:: Bytes {
189
+ /// Convert QByteArray to a `bytes::Bytes`. This makes a deep copy of the data.
190
+ fn from ( value : & QByteArray ) -> Self {
191
+ Self :: copy_from_slice ( value. as_ref ( ) )
192
+ }
193
+ }
194
+
179
195
impl QByteArray {
180
196
/// Inserts value at the end of the list.
181
197
pub fn append ( & mut self , ch : u8 ) {
@@ -199,12 +215,24 @@ impl QByteArray {
199
215
ffi:: qbytearray_fill ( self , ch, size)
200
216
}
201
217
218
+ /// Construct a QByteArray from a `bytes::Bytes` without a deep copy
219
+ ///
220
+ /// # Safety
221
+ ///
222
+ /// The caller must ensure that the original `bytes::Bytes` outlives the QByteArray
223
+ /// and that the QByteArray is not modified
224
+ #[ cfg( feature = "bytes" ) ]
225
+ pub unsafe fn from_raw_bytes ( bytes : & bytes:: Bytes ) -> Self {
226
+ Self :: from_raw_data ( bytes. as_ref ( ) )
227
+ }
228
+
202
229
/// Construct a QByteArray from a `&[u8]` without a deep copy
203
230
///
204
231
/// # Safety
205
232
///
206
233
/// The caller must ensure that the original slice outlives the QByteArray
207
- pub unsafe fn from_raw_data ( bytes : & [ u8 ] ) -> QByteArray {
234
+ /// and that the QByteArray is not modified
235
+ pub unsafe fn from_raw_data ( bytes : & [ u8 ] ) -> Self {
208
236
ffi:: qbytearray_from_raw_data ( bytes)
209
237
}
210
238
@@ -251,3 +279,20 @@ unsafe impl ExternType for QByteArray {
251
279
type Id = type_id ! ( "QByteArray" ) ;
252
280
type Kind = cxx:: kind:: Trivial ;
253
281
}
282
+
283
+ #[ cfg( test) ]
284
+ mod tests {
285
+ #[ cfg( feature = "bytes" ) ]
286
+ use super :: * ;
287
+
288
+ #[ cfg( feature = "bytes" ) ]
289
+ #[ test]
290
+ fn test_bytes ( ) {
291
+ let bytes = bytes:: Bytes :: from ( "KDAB" ) ;
292
+ let qbytearray = QByteArray :: from ( & bytes) ;
293
+ assert_eq ! ( bytes. as_ref( ) , qbytearray. as_ref( ) ) ;
294
+
295
+ let bytes_bytes = bytes:: Bytes :: from ( & qbytearray) ;
296
+ assert_eq ! ( bytes, bytes_bytes)
297
+ }
298
+ }
0 commit comments