Debian Codegraph @

third_party/rust/bytemuck_derive/tests/basic.rs

raw
1 #![allow(dead_code)]
2 #![deny(clippy::allow_attributes)]
3
4 use bytemuck::{
5 checked::CheckedCastError, AnyBitPattern, CheckedBitPattern, Contiguous,
6 NoUninit, Pod, TransparentWrapper, Zeroable,
7 };
8 use std::marker::{PhantomData, PhantomPinned};
9
10 #[derive(Copy, Clone, Pod, Zeroable)]
11 #[repr(C)]
12 struct Test {
13 a: u16,
14 b: u16,
15 }
16
17 #[derive(Pod, Zeroable)]
18 #[repr(C, packed)]
19 struct GenericPackedStruct<T: Pod> {
20 a: u32,
21 b: T,
22 c: u32,
23 }
24
25 impl<T: Pod> Clone for GenericPackedStruct<T> {
26 fn clone(&self) -> Self {
27 *self
28 }
29 }
30
31 impl<T: Pod> Copy for GenericPackedStruct<T> {}
32
33 #[derive(Pod, Zeroable)]
34 #[repr(C, packed(1))]
35 struct GenericPackedStructExplicitPackedAlignment<T: Pod> {
36 a: u32,
37 b: T,
38 c: u32,
39 }
40
41 impl<T: Pod> Clone for GenericPackedStructExplicitPackedAlignment<T> {
42 fn clone(&self) -> Self {
43 *self
44 }
45 }
46
47 impl<T: Pod> Copy for GenericPackedStructExplicitPackedAlignment<T> {}
48
49 #[derive(Zeroable)]
50 struct ZeroGeneric<T: bytemuck::Zeroable> {
51 a: T,
52 }
53
54 #[derive(Zeroable)]
55 #[repr(u8)]
56 enum ZeroEnum {
57 A = 0,
58 B = 1,
59 C = 2,
60 }
61
62 #[derive(Zeroable)]
63 #[repr(u8)]
64 enum BasicFieldfulZeroEnum {
65 A(u8) = 0,
66 B = 1,
67 C(String) = 2,
68 }
69
70 #[derive(Zeroable)]
71 #[repr(C)]
72 enum ReprCFieldfulZeroEnum {
73 A(u8),
74 B(Box<[u8]>),
75 C,
76 }
77
78 #[derive(Zeroable)]
79 #[repr(C, i32)]
80 enum ReprCIntFieldfulZeroEnum {
81 B(String) = 1,
82 A(u8, bool, char) = 0,
83 C = 2,
84 }
85
86 #[derive(Zeroable)]
87 #[repr(i32)]
88 enum GenericFieldfulZeroEnum<T> {
89 A(Box<T>) = 1,
90 B(T, T) = 0,
91 }
92
93 #[derive(Zeroable)]
94 #[repr(i32)]
95 #[zeroable(bound = "")]
96 enum GenericCustomBoundFieldfulZeroEnum<T> {
97 A(Option<Box<T>>),
98 B(String),
99 }
100
101 #[derive(TransparentWrapper)]
102 #[repr(transparent)]
103 struct TransparentSingle {
104 a: u16,
105 }
106
107 #[derive(TransparentWrapper)]
108 #[repr(transparent)]
109 #[transparent(u16)]
110 struct TransparentWithZeroSized<T> {
111 a: u16,
112 b: PhantomData<T>,
113 }
114
115 struct MyZst<T>(PhantomData<T>, [u8; 0], PhantomPinned);
116 unsafe impl<T> Zeroable for MyZst<T> {}
117
118 #[derive(TransparentWrapper)]
119 #[repr(transparent)]
120 #[transparent(u16)]
121 struct TransparentTupleWithCustomZeroSized<T>(u16, MyZst<T>);
122
123 #[repr(u8)]
124 #[derive(Clone, Copy, Contiguous)]
125 enum ContiguousWithValues {
126 A = 0,
127 B = 1,
128 C = 2,
129 D = 3,
130 E = 4,
131 }
132
133 #[repr(i8)]
134 #[derive(Clone, Copy, Contiguous)]
135 enum ContiguousWithImplicitValues {
136 A = -10,
137 B,
138 C,
139 D,
140 E,
141 }
142
143 #[derive(Copy, Clone, NoUninit)]
144 #[repr(C)]
145 struct NoUninitTest {
146 a: u16,
147 b: u16,
148 }
149
150 #[derive(Copy, Clone, AnyBitPattern)]
151 #[repr(C)]
152 union UnionTestAnyBitPattern {
153 a: u8,
154 b: u16,
155 }
156
157 #[repr(u8)]
158 #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
159 enum CheckedBitPatternEnumWithValues {
160 A = 0,
161 B = 1,
162 C = 2,
163 D = 3,
164 E = 4,
165 }
166
167 #[repr(i8)]
168 #[derive(Clone, Copy, NoUninit, CheckedBitPattern)]
169 enum CheckedBitPatternEnumWithImplicitValues {
170 A = -10,
171 B,
172 C,
173 D,
174 E,
175 }
176
177 #[repr(u8)]
178 #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
179 enum CheckedBitPatternEnumNonContiguous {
180 A = 1,
181 B = 8,
182 C = 2,
183 D = 3,
184 E = 56,
185 }
186
187 #[repr(u8)]
188 #[derive(Debug, Clone, Copy, NoUninit, CheckedBitPattern, PartialEq, Eq)]
189 enum CheckedBitPatternEnumByteLit {
190 A = b'A',
191 B = b'B',
192 C = b'C',
193 D = b'D',
194 E = b'E',
195 }
196
197 #[derive(Debug, Copy, Clone, NoUninit, CheckedBitPattern, PartialEq, Eq)]
198 #[repr(C)]
199 struct CheckedBitPatternStruct {
200 a: u8,
201 b: CheckedBitPatternEnumNonContiguous,
202 }
203
204 #[derive(Debug, Copy, Clone, AnyBitPattern, PartialEq, Eq)]
205 #[repr(C)]
206 struct AnyBitPatternTest<A: AnyBitPattern, B: AnyBitPattern> {
207 a: A,
208 b: B,
209 }
210
211 #[derive(Clone, Copy, CheckedBitPattern)]
212 #[repr(C, align(8))]
213 struct CheckedBitPatternAlignedStruct {
214 a: u16,
215 }
216
217 #[derive(Clone, Copy, CheckedBitPattern)]
218 #[repr(C, packed)]
219 struct CheckedBitPatternPackedStruct {
220 a: u8,
221 b: u16,
222 }
223
224 #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)]
225 #[repr(C)]
226 enum CheckedBitPatternCDefaultDiscriminantEnumWithFields {
227 A(u64),
228 B { c: u64 },
229 }
230
231 #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)]
232 #[repr(C, u8)]
233 enum CheckedBitPatternCEnumWithFields {
234 A(u32),
235 B { c: u32 },
236 }
237
238 #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)]
239 #[repr(u8)]
240 enum CheckedBitPatternIntEnumWithFields {
241 A(u8),
242 B { c: u32 },
243 }
244
245 #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)]
246 #[repr(transparent)]
247 enum CheckedBitPatternTransparentEnumWithFields {
248 A { b: u32 },
249 }
250
251 // size 24, align 8.
252 // first byte always the u8 discriminant, then 7 bytes of padding until the
253 // payload union since the align of the payload is the greatest of the align of
254 // all the variants, which is 8 (from
255 // CheckedBitPatternCDefaultDiscriminantEnumWithFields)
256 #[derive(Debug, Clone, Copy, CheckedBitPattern, PartialEq, Eq)]
257 #[repr(C, u8)]
258 enum CheckedBitPatternEnumNested {
259 A(CheckedBitPatternCEnumWithFields),
260 B(CheckedBitPatternCDefaultDiscriminantEnumWithFields),
261 }
262
263 /// ```compile_fail
264 /// use bytemuck::{Pod, Zeroable};
265 ///
266 /// #[derive(Pod, Zeroable)]
267 /// #[repr(transparent)]
268 /// struct TransparentSingle<T>(T);
269 ///
270 /// struct NotPod(u32);
271 ///
272 /// let _: u32 = bytemuck::cast(TransparentSingle(NotPod(0u32)));
273 /// ```
274 #[derive(
275 Debug, Copy, Clone, PartialEq, Eq, Pod, Zeroable, TransparentWrapper,
276 )]
277 #[repr(transparent)]
278 struct NewtypeWrapperTest<T>(T);
279
280 #[test]
281 fn fails_cast_contiguous() {
282 let can_cast = CheckedBitPatternEnumWithValues::is_valid_bit_pattern(&5);
283 assert!(!can_cast);
284 }
285
286 #[test]
287 fn passes_cast_contiguous() {
288 let res =
289 bytemuck::checked::from_bytes::<CheckedBitPatternEnumWithValues>(&[2u8]);
290 assert_eq!(*res, CheckedBitPatternEnumWithValues::C);
291 }
292
293 #[test]
294 fn fails_cast_noncontiguous() {
295 let can_cast = CheckedBitPatternEnumNonContiguous::is_valid_bit_pattern(&4);
296 assert!(!can_cast);
297 }
298
299 #[test]
300 fn passes_cast_noncontiguous() {
301 let res =
302 bytemuck::checked::from_bytes::<CheckedBitPatternEnumNonContiguous>(&[
303 56u8,
304 ]);
305 assert_eq!(*res, CheckedBitPatternEnumNonContiguous::E);
306 }
307
308 #[test]
309 fn fails_cast_bytelit() {
310 let can_cast = CheckedBitPatternEnumByteLit::is_valid_bit_pattern(&b'a');
311 assert!(!can_cast);
312 }
313
314 #[test]
315 fn passes_cast_bytelit() {
316 let res =
317 bytemuck::checked::cast_slice::<u8, CheckedBitPatternEnumByteLit>(b"CAB");
318 assert_eq!(
319 res,
320 [
321 CheckedBitPatternEnumByteLit::C,
322 CheckedBitPatternEnumByteLit::A,
323 CheckedBitPatternEnumByteLit::B
324 ]
325 );
326 }
327
328 #[test]
329 fn fails_cast_struct() {
330 let pod = [0u8, 24u8];
331 let res = bytemuck::checked::try_from_bytes::<CheckedBitPatternStruct>(&pod);
332 assert!(res.is_err());
333 }
334
335 #[test]
336 fn passes_cast_struct() {
337 let pod = [0u8, 8u8];
338 let res = bytemuck::checked::from_bytes::<CheckedBitPatternStruct>(&pod);
339 assert_eq!(
340 *res,
341 CheckedBitPatternStruct { a: 0, b: CheckedBitPatternEnumNonContiguous::B }
342 );
343 }
344
345 #[test]
346 fn anybitpattern_implies_zeroable() {
347 let test = AnyBitPatternTest::<isize, usize>::zeroed();
348 assert_eq!(test, AnyBitPatternTest { a: 0isize, b: 0usize });
349 }
350
351 #[test]
352 fn checkedbitpattern_try_pod_read_unaligned() {
353 let pod = [0u8];
354 let res = bytemuck::checked::try_pod_read_unaligned::<
355 CheckedBitPatternEnumWithValues,
356 >(&pod);
357 assert!(res.is_ok());
358
359 let pod = [5u8];
360 let res = bytemuck::checked::try_pod_read_unaligned::<
361 CheckedBitPatternEnumWithValues,
362 >(&pod);
363 assert!(res.is_err());
364 }
365
366 #[test]
367 fn checkedbitpattern_aligned_struct() {
368 let pod = [0u8; 8];
369 bytemuck::checked::pod_read_unaligned::<CheckedBitPatternAlignedStruct>(&pod);
370 }
371
372 #[test]
373 fn checkedbitpattern_c_default_discriminant_enum_with_fields() {
374 let pod = [
375 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0x55,
376 0x55, 0x55, 0x55, 0xcc,
377 ];
378 let value = bytemuck::checked::pod_read_unaligned::<
379 CheckedBitPatternCDefaultDiscriminantEnumWithFields,
380 >(&pod);
381 assert_eq!(
382 value,
383 CheckedBitPatternCDefaultDiscriminantEnumWithFields::A(0xcc555555555555cc)
384 );
385
386 let pod = [
387 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0x55,
388 0x55, 0x55, 0x55, 0xcc,
389 ];
390 let value = bytemuck::checked::pod_read_unaligned::<
391 CheckedBitPatternCDefaultDiscriminantEnumWithFields,
392 >(&pod);
393 assert_eq!(
394 value,
395 CheckedBitPatternCDefaultDiscriminantEnumWithFields::B {
396 c: 0xcc555555555555cc
397 }
398 );
399 }
400
401 #[test]
402 fn checkedbitpattern_c_enum_with_fields() {
403 let pod = [0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc];
404 let value = bytemuck::checked::pod_read_unaligned::<
405 CheckedBitPatternCEnumWithFields,
406 >(&pod);
407 assert_eq!(value, CheckedBitPatternCEnumWithFields::A(0xcc5555cc));
408
409 let pod = [0x01, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc];
410 let value = bytemuck::checked::pod_read_unaligned::<
411 CheckedBitPatternCEnumWithFields,
412 >(&pod);
413 assert_eq!(value, CheckedBitPatternCEnumWithFields::B { c: 0xcc5555cc });
414 }
415
416 #[test]
417 fn checkedbitpattern_int_enum_with_fields() {
418 let pod = [0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
419 let value = bytemuck::checked::pod_read_unaligned::<
420 CheckedBitPatternIntEnumWithFields,
421 >(&pod);
422 assert_eq!(value, CheckedBitPatternIntEnumWithFields::A(0x55));
423
424 let pod = [0x01, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55, 0xcc];
425 let value = bytemuck::checked::pod_read_unaligned::<
426 CheckedBitPatternIntEnumWithFields,
427 >(&pod);
428 assert_eq!(value, CheckedBitPatternIntEnumWithFields::B { c: 0xcc5555cc });
429 }
430
431 #[test]
432 fn checkedbitpattern_nested_enum_with_fields() {
433 // total size 24 bytes. first byte always the u8 discriminant.
434
435 #[repr(C, align(8))]
436 struct Align8Bytes([u8; 24]);
437
438 // first we'll check variantA, nested variant A
439 let pod = Align8Bytes([
440 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
441 0x00, // byte 0 discriminant = 0 = variant A, bytes 1-7 irrelevant padding.
442 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55,
443 0xcc, // bytes 8-15 are the nested CheckedBitPatternCEnumWithFields,
444 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bytes 16-23 padding
445 ]);
446 let value =
447 bytemuck::checked::from_bytes::<CheckedBitPatternEnumNested>(&pod.0);
448 assert_eq!(
449 value,
450 &CheckedBitPatternEnumNested::A(CheckedBitPatternCEnumWithFields::A(
451 0xcc5555cc
452 ))
453 );
454
455 // next we'll check invalid first discriminant fails
456 let pod = Align8Bytes([
457 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
458 0x00, // byte 0 discriminant = 2 = invalid, bytes 1-7 padding
459 0x00, 0x00, 0x00, 0x00, 0xcc, 0x55, 0x55,
460 0xcc, // bytes 8-15 are the nested CheckedBitPatternCEnumWithFields = A,
461 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bytes 16-23 padding
462 ]);
463 let result =
464 bytemuck::checked::try_from_bytes::<CheckedBitPatternEnumNested>(&pod.0);
465 assert_eq!(result, Err(CheckedCastError::InvalidBitPattern));
466
467 // next we'll check variant B, nested variant B
468 let pod = Align8Bytes([
469 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
470 0x00, // byte 0 discriminant = 1 = variant B, bytes 1-7 padding
471 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
472 0x00, /* bytes 8-15 is C int size discriminant of
473 * CheckedBitPatternCDefaultDiscrimimantEnumWithFields, 1 (LE byte
474 * order) = variant B */
475 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
476 0xcc, // bytes 16-13 is the data contained in nested variant B
477 ]);
478 let value =
479 bytemuck::checked::from_bytes::<CheckedBitPatternEnumNested>(&pod.0);
480 assert_eq!(
481 value,
482 &CheckedBitPatternEnumNested::B(
483 CheckedBitPatternCDefaultDiscriminantEnumWithFields::B {
484 c: 0xcc555555555555cc
485 }
486 )
487 );
488
489 // finally we'll check variant B, nested invalid discriminant
490 let pod = Align8Bytes([
491 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
492 0x00, // 1 discriminant = variant B, bytes 1-7 padding
493 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
494 0x00, /* bytes 8-15 is C int size discriminant of
495 * CheckedBitPatternCDefaultDiscrimimantEnumWithFields, 0x08 is
496 * invalid */
497 0xcc, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
498 0xcc, // bytes 16-13 is the data contained in nested variant B
499 ]);
500 let result =
501 bytemuck::checked::try_from_bytes::<CheckedBitPatternEnumNested>(&pod.0);
502 assert_eq!(result, Err(CheckedCastError::InvalidBitPattern));
503 }
504 #[test]
505 fn checkedbitpattern_transparent_enum_with_fields() {
506 let pod = [0xcc, 0x55, 0x55, 0xcc];
507 let value = bytemuck::checked::pod_read_unaligned::<
508 CheckedBitPatternTransparentEnumWithFields,
509 >(&pod);
510 assert_eq!(
511 value,
512 CheckedBitPatternTransparentEnumWithFields::A { b: 0xcc5555cc }
513 );
514 }
515
516 #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
517 #[repr(C, align(16))]
518 struct Issue127 {}
519
520 use bytemuck as reexport_name;
521 #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable, bytemuck::ByteEq)]
522 #[bytemuck(crate = "reexport_name")]
523 #[repr(C)]
524 struct Issue93 {}