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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
//! # bytecheck
//!
//! bytecheck is a memory validation framework for Rust.
//!
//! For some types, creating an invalid value immediately results in undefined
//! behavior. This can cause some issues when trying to validate potentially
//! invalid bytes, as just casting the bytes to your type can technically cause
//! errors. This makes it difficult to write validation routines, because until
//! you're certain that the bytes represent valid values you cannot cast them.
//!
//! bytecheck provides a framework for performing these byte-level validations
//! and implements checks for basic types along with a derive macro to implement
//! validation for custom structs and enums.
//!
//! ## Design
//!
//! [`CheckBytes`] is at the heart of bytecheck, and does the heavy lifting of
//! verifying that some bytes represent a valid type. Implementing it can be
//! done manually or automatically with the [derive macro](macro@CheckBytes).
//!
//! ## Layout stability
//!
//! The layouts of types may change between compiler versions, or even different
//! compilations. To guarantee stable type layout between compilations, structs,
//! enums, and unions can be annotated with `#[repr(C)]`, and enums specifically
//! can be annotated with `#[repr(int)]` or `#[repr(C, int)]` as well. See
//! [the reference's page on type layout][reference] for more details.
//!
//! [reference]: https://doc.rust-lang.org/reference/type-layout.html
//!
//! ## Features
//!
//! - `derive`: Re-exports the macros from `bytecheck_derive`. Enabled by
//! default.
//! - `simdutf8`: Uses the `simdutf8` crate to validate UTF-8 strings. Enabled
//! by default.
//!
//! ### Crates
//!
//! Bytecheck provides integrations for some common crates by default. In the
//! future, crates should depend on bytecheck and provide their own integration.
//!
//! - [`uuid-1`](https://docs.rs/uuid/1)
//!
//! ## Example
#![doc = include_str!("../example.md")]
#![deny(
future_incompatible,
missing_docs,
nonstandard_style,
unsafe_op_in_unsafe_fn,
unused,
warnings,
clippy::all,
clippy::missing_safety_doc,
clippy::undocumented_unsafe_blocks,
rustdoc::broken_intra_doc_links,
rustdoc::missing_crate_level_docs
)]
#![no_std]
#![cfg_attr(all(docsrs, not(doctest)), feature(doc_cfg, doc_auto_cfg))]
// Support for various common crates. These are primarily to get users off the
// ground and build some momentum.
// These are NOT PLANNED to remain in bytecheck for the final release. Much like
// serde, these implementations should be moved into their respective crates
// over time. Before adding support for another crate, please consider getting
// bytecheck support in the crate instead.
#[cfg(feature = "uuid-1")]
mod uuid;
#[cfg(not(feature = "simdutf8"))]
use core::str::from_utf8;
#[cfg(target_has_atomic = "8")]
use core::sync::atomic::{AtomicBool, AtomicI8, AtomicU8};
#[cfg(target_has_atomic = "16")]
use core::sync::atomic::{AtomicI16, AtomicU16};
#[cfg(target_has_atomic = "32")]
use core::sync::atomic::{AtomicI32, AtomicU32};
#[cfg(target_has_atomic = "64")]
use core::sync::atomic::{AtomicI64, AtomicU64};
use core::{
cell::{Cell, UnsafeCell},
error::Error,
ffi::CStr,
fmt,
marker::{PhantomData, PhantomPinned},
mem::ManuallyDrop,
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8,
},
ops, ptr,
};
pub use bytecheck_derive::CheckBytes;
pub use rancor;
use rancor::{fail, Fallible, ResultExt as _, Source, Strategy, Trace};
#[cfg(feature = "simdutf8")]
use simdutf8::basic::from_utf8;
/// A type that can check whether a pointer points to a valid value.
///
/// `CheckBytes` can be derived with [`CheckBytes`](macro@CheckBytes) or
/// implemented manually for custom behavior.
///
/// # Safety
///
/// `check_bytes` must only return `Ok` if `value` points to a valid instance of
/// `Self`. Because `value` must always be properly aligned for `Self` and point
/// to enough bytes to represent the type, this implies that `value` may be
/// dereferenced safely.
///
/// # Example
///
/// ```
/// use core::{error::Error, fmt};
///
/// use bytecheck::CheckBytes;
/// use rancor::{fail, Fallible, Source};
///
/// #[repr(C, align(4))]
/// pub struct NonMaxU32(u32);
///
/// unsafe impl<C: Fallible + ?Sized> CheckBytes<C> for NonMaxU32
/// where
/// C::Error: Source,
/// {
/// unsafe fn check_bytes(
/// value: *const Self,
/// context: &mut C,
/// ) -> Result<(), C::Error> {
/// #[derive(Debug)]
/// struct NonMaxCheckError;
///
/// impl fmt::Display for NonMaxCheckError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "non-max u32 was set to u32::MAX")
/// }
/// }
///
/// impl Error for NonMaxCheckError {}
///
/// let value = unsafe { value.read() };
/// if value.0 == u32::MAX {
/// fail!(NonMaxCheckError);
/// }
///
/// Ok(())
/// }
/// }
/// ```
///
/// See [`Verify`] for an example which uses less unsafe.
pub unsafe trait CheckBytes<C: Fallible + ?Sized> {
/// Checks whether the given pointer points to a valid value within the
/// given context.
///
/// # Safety
///
/// The passed pointer must be aligned and point to enough initialized bytes
/// to represent the type.
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error>;
}
/// A type that can check whether its invariants are upheld.
///
/// When using [the derive](macro@CheckBytes), adding `#[bytecheck(verify)]`
/// allows implementing `Verify` for the derived type. [`Verify::verify`] will
/// be called after the type is checked and all fields are known to be valid.
///
/// # Safety
///
/// - `verify` must only return `Ok` if all of the invariants of this type are
/// upheld by `self`.
/// - `verify` may not assume that its type invariants are upheld by the given
/// `self` (the invariants of each field are guaranteed to be upheld).
///
/// # Example
///
/// ```
/// use core::{error::Error, fmt};
///
/// use bytecheck::{CheckBytes, Verify};
/// use rancor::{fail, Fallible, Source};
///
/// #[derive(CheckBytes)]
/// #[bytecheck(verify)]
/// #[repr(C, align(4))]
/// pub struct NonMaxU32(u32);
///
/// unsafe impl<C: Fallible + ?Sized> Verify<C> for NonMaxU32
/// where
/// C::Error: Source,
/// {
/// fn verify(&self, context: &mut C) -> Result<(), C::Error> {
/// #[derive(Debug)]
/// struct NonMaxCheckError;
///
/// impl fmt::Display for NonMaxCheckError {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "non-max u32 was set to u32::MAX")
/// }
/// }
///
/// impl Error for NonMaxCheckError {}
///
/// if self.0 == u32::MAX {
/// fail!(NonMaxCheckError);
/// }
///
/// Ok(())
/// }
/// }
/// ```
pub unsafe trait Verify<C: Fallible + ?Sized> {
/// Checks whether the invariants of this type are upheld by `self`.
fn verify(&self, context: &mut C) -> Result<(), C::Error>;
}
/// Checks whether the given pointer points to a valid value.
///
/// # Safety
///
/// The passed pointer must be aligned and point to enough initialized bytes to
/// represent the type.
///
/// # Example
///
/// ```
/// use bytecheck::check_bytes;
/// use rancor::Failure;
///
/// unsafe {
/// // 0 and 1 are valid values for bools
/// check_bytes::<bool, Failure>((&0u8 as *const u8).cast()).unwrap();
/// check_bytes::<bool, Failure>((&1u8 as *const u8).cast()).unwrap();
///
/// // 2 is not a valid value
/// check_bytes::<bool, Failure>((&2u8 as *const u8).cast()).unwrap_err();
/// }
/// ```
#[inline]
pub unsafe fn check_bytes<T, E>(value: *const T) -> Result<(), E>
where
T: CheckBytes<Strategy<(), E>> + ?Sized,
{
// SAFETY: The safety conditions of `check_bytes_with_context` are the same
// as the safety conditions of this function.
unsafe { check_bytes_with_context(value, &mut ()) }
}
/// Checks whether the given pointer points to a valid value within the given
/// context.
///
/// # Safety
///
/// The passed pointer must be aligned and point to enough initialized bytes to
/// represent the type.
///
/// # Example
///
/// ```
/// use core::{error::Error, fmt};
///
/// use bytecheck::{check_bytes_with_context, CheckBytes, Verify};
/// use rancor::{fail, Failure, Fallible, Source, Strategy};
///
/// trait Context {
/// fn is_allowed(&self, value: u8) -> bool;
/// }
///
/// impl<T: Context + ?Sized, E> Context for Strategy<T, E> {
/// fn is_allowed(&self, value: u8) -> bool {
/// T::is_allowed(self, value)
/// }
/// }
///
/// struct Allowed(u8);
///
/// impl Context for Allowed {
/// fn is_allowed(&self, value: u8) -> bool {
/// value == self.0
/// }
/// }
///
/// #[derive(CheckBytes)]
/// #[bytecheck(verify)]
/// #[repr(C)]
/// pub struct ContextualByte(u8);
///
/// unsafe impl<C: Context + Fallible + ?Sized> Verify<C> for ContextualByte
/// where
/// C::Error: Source,
/// {
/// fn verify(&self, context: &mut C) -> Result<(), C::Error> {
/// #[derive(Debug)]
/// struct InvalidByte(u8);
///
/// impl fmt::Display for InvalidByte {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// write!(f, "invalid contextual byte: {}", self.0)
/// }
/// }
///
/// impl Error for InvalidByte {}
///
/// if !context.is_allowed(self.0) {
/// fail!(InvalidByte(self.0));
/// }
///
/// Ok(())
/// }
/// }
///
/// let value = 45u8;
/// unsafe {
/// // Checking passes when the context allows byte 45
/// check_bytes_with_context::<ContextualByte, _, Failure>(
/// (&value as *const u8).cast(),
/// &mut Allowed(45),
/// )
/// .unwrap();
///
/// // Checking fails when the conteext does not allow byte 45
/// check_bytes_with_context::<ContextualByte, _, Failure>(
/// (&value as *const u8).cast(),
/// &mut Allowed(0),
/// )
/// .unwrap_err();
/// }
/// ```
pub unsafe fn check_bytes_with_context<T, C, E>(
value: *const T,
context: &mut C,
) -> Result<(), E>
where
T: CheckBytes<Strategy<C, E>> + ?Sized,
{
// SAFETY: The safety conditions of `check_bytes` are the same as the safety
// conditions of this function.
unsafe { CheckBytes::check_bytes(value, Strategy::wrap(context)) }
}
macro_rules! impl_primitive {
($type:ty) => {
// SAFETY: All bit patterns are valid for these primitive types.
unsafe impl<C: Fallible + ?Sized> CheckBytes<C> for $type {
#[inline]
unsafe fn check_bytes(
_: *const Self,
_: &mut C,
) -> Result<(), C::Error> {
Ok(())
}
}
};
}
macro_rules! impl_primitives {
($($type:ty),* $(,)?) => {
$(
impl_primitive!($type);
)*
}
}
impl_primitives! {
(),
i8, i16, i32, i64, i128,
u8, u16, u32, u64, u128,
f32, f64,
}
#[cfg(target_has_atomic = "8")]
impl_primitives!(AtomicI8, AtomicU8);
#[cfg(target_has_atomic = "16")]
impl_primitives!(AtomicI16, AtomicU16);
#[cfg(target_has_atomic = "32")]
impl_primitives!(AtomicI32, AtomicU32);
#[cfg(target_has_atomic = "64")]
impl_primitives!(AtomicI64, AtomicU64);
// SAFETY: `PhantomData` is a zero-sized type and so all bit patterns are valid.
unsafe impl<T: ?Sized, C: Fallible + ?Sized> CheckBytes<C> for PhantomData<T> {
#[inline]
unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), C::Error> {
Ok(())
}
}
// SAFETY: `PhantomPinned` is a zero-sized type and so all bit patterns are
// valid.
unsafe impl<C: Fallible + ?Sized> CheckBytes<C> for PhantomPinned {
#[inline]
unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), C::Error> {
Ok(())
}
}
// SAFETY: `ManuallyDrop<T>` is a `#[repr(transparent)]` wrapper around a `T`,
// and so `value` points to a valid `ManuallyDrop<T>` if it also points to a
// valid `T`.
unsafe impl<T, C> CheckBytes<C> for ManuallyDrop<T>
where
T: CheckBytes<C> + ?Sized,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
c: &mut C,
) -> Result<(), C::Error> {
// SAFETY: Because `ManuallyDrop<T>` is `#[repr(transparent)]`, a
// pointer to a `ManuallyDrop<T>` is guaranteed to be the same as a
// pointer to `T`. We can't call `.cast()` here because `T` may be
// an unsized type.
let inner_ptr =
unsafe { core::mem::transmute::<*const Self, *const T>(value) };
// SAFETY: The caller has guaranteed that `value` is aligned for
// `ManuallyDrop<T>` and points to enough bytes to represent
// `ManuallyDrop<T>`. Since `ManuallyDrop<T>` is `#[repr(transparent)]`,
// `inner_ptr` is also aligned for `T` and points to enough bytes to
// represent it.
unsafe {
T::check_bytes(inner_ptr, c)
.trace("while checking inner value of `ManuallyDrop`")
}
}
}
// SAFETY: `UnsafeCell<T>` has the same memory layout as `T`, and so `value`
// points to a valid `UnsafeCell<T>` if it also points to a valid `T`.
unsafe impl<T, C> CheckBytes<C> for UnsafeCell<T>
where
T: CheckBytes<C> + ?Sized,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
c: &mut C,
) -> Result<(), C::Error> {
// SAFETY: Because `UnsafeCell<T>` has the same memory layout as
// `T`, a pointer to an `UnsafeCell<T>` is guaranteed to be the same
// as a pointer to `T`. We can't call `.cast()` here because `T` may
// be an unsized type.
let inner_ptr =
unsafe { core::mem::transmute::<*const Self, *const T>(value) };
// SAFETY: The caller has guaranteed that `value` is aligned for
// `UnsafeCell<T>` and points to enough bytes to represent
// `UnsafeCell<T>`. Since `UnsafeCell<T>` has the same layout `T`,
// `inner_ptr` is also aligned for `T` and points to enough bytes to
// represent it.
unsafe {
T::check_bytes(inner_ptr, c)
.trace("while checking inner value of `UnsafeCell`")
}
}
}
// SAFETY: `Cell<T>` has the same memory layout as `UnsafeCell<T>` (and
// therefore `T` itself), and so `value` points to a valid `UnsafeCell<T>` if it
// also points to a valid `T`.
unsafe impl<T, C> CheckBytes<C> for Cell<T>
where
T: CheckBytes<C> + ?Sized,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
c: &mut C,
) -> Result<(), C::Error> {
// SAFETY: Because `Cell<T>` has the same memory layout as
// `UnsafeCell<T>` (and therefore `T` itself), a pointer to a
// `Cell<T>` is guaranteed to be the same as a pointer to `T`. We
// can't call `.cast()` here because `T` may be an unsized type.
let inner_ptr =
unsafe { core::mem::transmute::<*const Self, *const T>(value) };
// SAFETY: The caller has guaranteed that `value` is aligned for
// `Cell<T>` and points to enough bytes to represent `Cell<T>`. Since
// `Cell<T>` has the same layout as `UnsafeCell<T>` ( and therefore `T`
// itself), `inner_ptr` is also aligned for `T` and points to enough
// bytes to represent it.
unsafe {
T::check_bytes(inner_ptr, c)
.trace("while checking inner value of `Cell`")
}
}
}
#[derive(Debug)]
struct BoolCheckError {
byte: u8,
}
impl fmt::Display for BoolCheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"bool set to invalid byte {}, expected either 0 or 1",
self.byte,
)
}
}
impl Error for BoolCheckError {}
// SAFETY: A bool is a one byte value that must either be 0 or 1. `check_bytes`
// only returns `Ok` if `value` is 0 or 1.
unsafe impl<C> CheckBytes<C> for bool
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
_: &mut C,
) -> Result<(), C::Error> {
// SAFETY: `value` is a pointer to a `bool`, which has a size and
// alignment of one. `u8` also has a size and alignment of one, and all
// bit patterns are valid for `u8`. So we can cast `value` to a `u8`
// pointer and read from it.
let byte = unsafe { *value.cast::<u8>() };
match byte {
0 | 1 => Ok(()),
_ => fail!(BoolCheckError { byte }),
}
}
}
#[cfg(target_has_atomic = "8")]
// SAFETY: `AtomicBool` has the same ABI as `bool`, so if `value` points to a
// valid `bool` then it also points to a valid `AtomicBool`.
unsafe impl<C> CheckBytes<C> for AtomicBool
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
// SAFETY: `AtomicBool` has the same ABI as `bool`, so a pointer that is
// aligned for `AtomicBool` and points to enough bytes for `AtomicBool`
// is also aligned for `bool` and points to enough bytes for `bool`.
unsafe { bool::check_bytes(value.cast(), context) }
}
}
// SAFETY: If `char::try_from` succeeds with the pointed-to-value, then it must
// be a valid value for `char`.
unsafe impl<C> CheckBytes<C> for char
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(ptr: *const Self, _: &mut C) -> Result<(), C::Error> {
// SAFETY: `char` and `u32` are both four bytes, but we're not
// guaranteed that they have the same alignment. Using `read_unaligned`
// ensures that we can read a `u32` regardless and try to convert it to
// a `char`.
let value = unsafe { ptr.cast::<u32>().read_unaligned() };
char::try_from(value).into_error()?;
Ok(())
}
}
#[derive(Debug)]
struct TupleIndexContext {
index: usize,
}
impl fmt::Display for TupleIndexContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "while checking index {} of tuple", self.index)
}
}
macro_rules! impl_tuple {
($($type:ident $index:tt),*) => {
// SAFETY: A tuple is valid if all of its elements are valid, and
// `check_bytes` only returns `Ok` when all of the elements validated
// successfully.
unsafe impl<$($type,)* C> CheckBytes<C> for ($($type,)*)
where
$($type: CheckBytes<C>,)*
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
#[allow(clippy::unneeded_wildcard_pattern)]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
$(
// SAFETY: The caller has guaranteed that `value` points to
// enough bytes for this tuple and is properly aligned, so
// we can create pointers to each element and check them.
unsafe {
<$type>::check_bytes(
ptr::addr_of!((*value).$index),
context,
).with_trace(|| TupleIndexContext { index: $index })?;
}
)*
Ok(())
}
}
}
}
impl_tuple!(T0 0);
impl_tuple!(T0 0, T1 1);
impl_tuple!(T0 0, T1 1, T2 2);
impl_tuple!(T0 0, T1 1, T2 2, T3 3);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9);
impl_tuple!(T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10);
impl_tuple!(
T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11
);
impl_tuple!(
T0 0, T1 1, T2 2, T3 3, T4 4, T5 5, T6 6, T7 7, T8 8, T9 9, T10 10, T11 11,
T12 12
);
#[derive(Debug)]
struct ArrayCheckContext {
index: usize,
}
impl fmt::Display for ArrayCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "while checking index '{}' of array", self.index)
}
}
// SAFETY: `check_bytes` only returns `Ok` if each element of the array is
// valid. If each element of the array is valid then the whole array is also
// valid.
unsafe impl<T, const N: usize, C> CheckBytes<C> for [T; N]
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
let base = value.cast::<T>();
for index in 0..N {
// SAFETY: The caller has guaranteed that `value` points to enough
// bytes for this array and is properly aligned, so we can create
// pointers to each element and check them.
unsafe {
T::check_bytes(base.add(index), context)
.with_trace(|| ArrayCheckContext { index })?;
}
}
Ok(())
}
}
#[derive(Debug)]
struct SliceCheckContext {
index: usize,
}
impl fmt::Display for SliceCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "while checking index '{}' of slice", self.index)
}
}
// SAFETY: `check_bytes` only returns `Ok` if each element of the slice is
// valid. If each element of the slice is valid then the whole slice is also
// valid.
unsafe impl<T, C> CheckBytes<C> for [T]
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
let (data_address, len) = ptr_meta::to_raw_parts(value);
let base = data_address.cast::<T>();
for index in 0..len {
// SAFETY: The caller has guaranteed that `value` points to enough
// bytes for this slice and is properly aligned, so we can create
// pointers to each element and check them.
unsafe {
T::check_bytes(base.add(index), context)
.with_trace(|| SliceCheckContext { index })?;
}
}
Ok(())
}
}
// SAFETY: `check_bytes` only returns `Ok` if the bytes pointed to by `str` are
// valid UTF-8. If they are valid UTF-8 then the overall `str` is also valid.
unsafe impl<C> CheckBytes<C> for str
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
_: &mut C,
) -> Result<(), C::Error> {
#[derive(Debug)]
struct Utf8Error;
impl fmt::Display for Utf8Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid UTF-8")
}
}
impl Error for Utf8Error {}
let slice_ptr = value as *const [u8];
// SAFETY: The caller has guaranteed that `value` is properly-aligned
// and points to enough bytes for its `str`. Because a `u8` slice has
// the same layout as a `str`, we can dereference it for UTF-8
// validation.
let slice = unsafe { &*slice_ptr };
from_utf8(slice).map_err(|_| Utf8Error).into_error()?;
Ok(())
}
}
// SAFETY: `check_bytes` only returns `Ok` when the bytes constitute a valid
// `CStr` per `CStr::from_bytes_with_nul`.
unsafe impl<C> CheckBytes<C> for CStr
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
_: &mut C,
) -> Result<(), C::Error> {
let slice_ptr = value as *const [u8];
// SAFETY: The caller has guaranteed that `value` is properly-aligned
// and points to enough bytes for its `CStr`. Because a `u8` slice has
// the same layout as a `CStr`, we can dereference it for validation.
let slice = unsafe { &*slice_ptr };
CStr::from_bytes_with_nul(slice).into_error()?;
Ok(())
}
}
// Generic contexts used by the derive.
/// Context for errors resulting from invalid structs.
///
/// This context is used by the derive macro to trace which field of a struct
/// failed validation.
#[derive(Debug)]
pub struct StructCheckContext {
/// The name of the struct with an invalid field.
pub struct_name: &'static str,
/// The name of the struct field that was invalid.
pub field_name: &'static str,
}
impl fmt::Display for StructCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"while checking field '{}' of struct '{}'",
self.field_name, self.struct_name
)
}
}
/// Context for errors resulting from invalid tuple structs.
///
/// This context is used by the derive macro to trace which field of a tuple
/// struct failed validation.
#[derive(Debug)]
pub struct TupleStructCheckContext {
/// The name of the tuple struct with an invalid field.
pub tuple_struct_name: &'static str,
/// The index of the tuple struct field that was invalid.
pub field_index: usize,
}
impl fmt::Display for TupleStructCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"while checking field index {} of tuple struct '{}'",
self.field_index, self.tuple_struct_name,
)
}
}
/// An error resulting from an invalid enum tag.
///
/// This context is used by the derive macro to trace what the invalid
/// discriminant for an enum is.
#[derive(Debug)]
pub struct InvalidEnumDiscriminantError<T> {
/// The name of the enum with an invalid discriminant.
pub enum_name: &'static str,
/// The invalid value of the enum discriminant.
pub invalid_discriminant: T,
}
impl<T: fmt::Display> fmt::Display for InvalidEnumDiscriminantError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid discriminant '{}' for enum '{}'",
self.invalid_discriminant, self.enum_name
)
}
}
impl<T> Error for InvalidEnumDiscriminantError<T> where
T: fmt::Debug + fmt::Display
{
}
/// Context for errors resulting from checking enum variants with named fields.
///
/// This context is used by the derive macro to trace which field of an enum
/// variant failed validation.
#[derive(Debug)]
pub struct NamedEnumVariantCheckContext {
/// The name of the enum with an invalid variant.
pub enum_name: &'static str,
/// The name of the variant that was invalid.
pub variant_name: &'static str,
/// The name of the field that was invalid.
pub field_name: &'static str,
}
impl fmt::Display for NamedEnumVariantCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"while checking field '{}' of variant '{}' of enum '{}'",
self.field_name, self.variant_name, self.enum_name,
)
}
}
/// Context for errors resulting from checking enum variants with unnamed
/// fields.
///
/// This context is used by the derive macro to trace which field of an enum
/// variant failed validation.
#[derive(Debug)]
pub struct UnnamedEnumVariantCheckContext {
/// The name of the enum with an invalid variant.
pub enum_name: &'static str,
/// The name of the variant that was invalid.
pub variant_name: &'static str,
/// The name of the field that was invalid.
pub field_index: usize,
}
impl fmt::Display for UnnamedEnumVariantCheckContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"while checking field index {} of variant '{}' of enum '{}'",
self.field_index, self.variant_name, self.enum_name,
)
}
}
// Range types
// SAFETY: A `Range<T>` is valid if its `start` and `end` are both valid, and
// `check_bytes` only returns `Ok` when both `start` and `end` are valid. Note
// that `Range` does not require `start` be less than `end`.
unsafe impl<T, C> CheckBytes<C> for ops::Range<T>
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
// SAFETY: The caller has guaranteed that `value` is aligned for a
// `Range<T>` and points to enough initialized bytes for one, so a
// pointer projected to the `start` field will be properly aligned for
// a `T` and point to enough initialized bytes for one too.
unsafe {
T::check_bytes(ptr::addr_of!((*value).start), context).with_trace(
|| StructCheckContext {
struct_name: "Range",
field_name: "start",
},
)?;
}
// SAFETY: Same reasoning as above, but for `end`.
unsafe {
T::check_bytes(ptr::addr_of!((*value).end), context).with_trace(
|| StructCheckContext {
struct_name: "Range",
field_name: "end",
},
)?;
}
Ok(())
}
}
// SAFETY: A `RangeFrom<T>` is valid if its `start` is valid, and `check_bytes`
// only returns `Ok` when its `start` is valid.
unsafe impl<T, C> CheckBytes<C> for ops::RangeFrom<T>
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
// SAFETY: The caller has guaranteed that `value` is aligned for a
// `RangeFrom<T>` and points to enough initialized bytes for one, so a
// pointer projected to the `start` field will be properly aligned for
// a `T` and point to enough initialized bytes for one too.
unsafe {
T::check_bytes(ptr::addr_of!((*value).start), context).with_trace(
|| StructCheckContext {
struct_name: "RangeFrom",
field_name: "start",
},
)?;
}
Ok(())
}
}
// SAFETY: `RangeFull` is a ZST and so every pointer to one is valid.
unsafe impl<C: Fallible + ?Sized> CheckBytes<C> for ops::RangeFull {
#[inline]
unsafe fn check_bytes(_: *const Self, _: &mut C) -> Result<(), C::Error> {
Ok(())
}
}
// SAFETY: A `RangeTo<T>` is valid if its `end` is valid, and `check_bytes` only
// returns `Ok` when its `end` is valid.
unsafe impl<T, C> CheckBytes<C> for ops::RangeTo<T>
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
// SAFETY: The caller has guaranteed that `value` is aligned for a
// `RangeTo<T>` and points to enough initialized bytes for one, so a
// pointer projected to the `end` field will be properly aligned for
// a `T` and point to enough initialized bytes for one too.
unsafe {
T::check_bytes(ptr::addr_of!((*value).end), context).with_trace(
|| StructCheckContext {
struct_name: "RangeTo",
field_name: "end",
},
)?;
}
Ok(())
}
}
// SAFETY: A `RangeToInclusive<T>` is valid if its `end` is valid, and
// `check_bytes` only returns `Ok` when its `end` is valid.
unsafe impl<T, C> CheckBytes<C> for ops::RangeToInclusive<T>
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
C::Error: Trace,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
// SAFETY: The caller has guaranteed that `value` is aligned for a
// `RangeToInclusive<T>` and points to enough initialized bytes for one,
// so a pointer projected to the `end` field will be properly aligned
// for a `T` and point to enough initialized bytes for one too.
unsafe {
T::check_bytes(ptr::addr_of!((*value).end), context).with_trace(
|| StructCheckContext {
struct_name: "RangeToInclusive",
field_name: "end",
},
)?;
}
Ok(())
}
}
#[derive(Debug)]
struct NonZeroCheckError;
impl fmt::Display for NonZeroCheckError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "nonzero integer is zero")
}
}
impl Error for NonZeroCheckError {}
macro_rules! impl_nonzero {
($nonzero:ident, $underlying:ident) => {
// SAFETY: `check_bytes` only returns `Ok` when `value` is not zero, the
// only validity condition for non-zero integer types.
unsafe impl<C> CheckBytes<C> for $nonzero
where
C: Fallible + ?Sized,
C::Error: Source,
{
#[inline]
unsafe fn check_bytes(
value: *const Self,
_: &mut C,
) -> Result<(), C::Error> {
// SAFETY: Non-zero integer types are guaranteed to have the
// same ABI as their corresponding integer types. Those integers
// have no validity requirements, so we can cast and dereference
// value to check if it is equal to zero.
if unsafe { *value.cast::<$underlying>() } == 0 {
fail!(NonZeroCheckError);
} else {
Ok(())
}
}
}
};
}
impl_nonzero!(NonZeroI8, i8);
impl_nonzero!(NonZeroI16, i16);
impl_nonzero!(NonZeroI32, i32);
impl_nonzero!(NonZeroI64, i64);
impl_nonzero!(NonZeroI128, i128);
impl_nonzero!(NonZeroU8, u8);
impl_nonzero!(NonZeroU16, u16);
impl_nonzero!(NonZeroU32, u32);
impl_nonzero!(NonZeroU64, u64);
impl_nonzero!(NonZeroU128, u128);
#[cfg(test)]
#[macro_use]
mod tests {
use core::ffi::CStr;
use rancor::{Failure, Fallible, Infallible, Source, Strategy};
use crate::{check_bytes, check_bytes_with_context, CheckBytes, Verify};
#[derive(Debug)]
#[repr(transparent)]
struct CharLE(u32);
impl From<char> for CharLE {
fn from(c: char) -> Self {
#[cfg(target_endian = "little")]
{
Self(c as u32)
}
#[cfg(target_endian = "big")]
{
Self((c as u32).swap_bytes())
}
}
}
unsafe impl<C> CheckBytes<C> for CharLE
where
C: Fallible + ?Sized,
C::Error: Source,
{
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
#[cfg(target_endian = "little")]
unsafe {
char::check_bytes(value.cast(), context)
}
#[cfg(target_endian = "big")]
unsafe {
let mut bytes = *value.cast::<[u8; 4]>();
bytes.reverse();
char::check_bytes(bytes.as_ref().as_ptr().cast(), context)
}
}
}
#[repr(C, align(16))]
struct Aligned<const N: usize>(pub [u8; N]);
macro_rules! bytes {
($($byte:literal),* $(,)?) => {
(&$crate::tests::Aligned([$($byte,)*]).0 as &[u8]).as_ptr()
}
}
#[test]
fn test_tuples() {
unsafe {
check_bytes::<_, Failure>(&(42u32, true, 'x')).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&(true,)).unwrap();
}
unsafe {
// These tests assume the tuple is packed (u32, bool, char)
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, 0x78u8, 0u8,
0u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
42u8, 16u8, 20u8, 3u8, 1u8, 255u8, 255u8, 255u8, 0x78u8,
0u8, 0u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, 0x00u8,
0xd8u8, 0u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8, 0x00u8,
0x00u8, 0x11u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0u8, 255u8, 255u8, 255u8, 0x78u8, 0u8,
0u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<(u32, bool, CharLE), Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 2u8, 255u8, 255u8, 255u8, 0x78u8, 0u8,
0u8, 0u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
}
}
#[test]
fn test_arrays() {
unsafe {
check_bytes::<_, Failure>(&[true, false, true, false]).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&[false, true]).unwrap();
}
unsafe {
check_bytes::<[bool; 4], Failure>(
bytes![1u8, 0u8, 1u8, 0u8].cast(),
)
.unwrap();
check_bytes::<[bool; 4], Failure>(
bytes![1u8, 2u8, 1u8, 0u8].cast(),
)
.unwrap_err();
check_bytes::<[bool; 4], Failure>(
bytes![2u8, 0u8, 1u8, 0u8].cast(),
)
.unwrap_err();
check_bytes::<[bool; 4], Failure>(
bytes![1u8, 0u8, 1u8, 2u8].cast(),
)
.unwrap_err();
check_bytes::<[bool; 4], Failure>(
bytes![1u8, 0u8, 1u8, 0u8, 2u8].cast(),
)
.unwrap();
}
}
#[test]
fn test_unsized() {
unsafe {
check_bytes::<[i32], Infallible>(
&[1, 2, 3, 4] as &[i32] as *const [i32]
)
.unwrap();
check_bytes::<str, Failure>("hello world" as *const str).unwrap();
}
}
#[test]
fn test_c_str() {
macro_rules! test_cases {
($($bytes:expr, $pat:pat,)*) => {
$(
let bytes = $bytes;
let c_str = ::ptr_meta::from_raw_parts(
bytes.as_ptr().cast(),
bytes.len(),
);
assert!(matches!(
check_bytes::<CStr, Failure>(c_str),
$pat,
));
)*
}
}
unsafe {
test_cases! {
b"hello world\0", Ok(_),
b"hello world", Err(_),
b"", Err(_),
[0xc3u8, 0x28u8, 0x00u8], Ok(_),
[0xc3u8, 0x28u8, 0x00u8, 0xc3u8, 0x28u8, 0x00u8], Err(_),
}
}
}
#[test]
fn test_unit_struct() {
#[derive(CheckBytes)]
#[bytecheck(crate)]
struct Test;
unsafe {
check_bytes::<_, Infallible>(&Test).unwrap();
}
}
#[test]
fn test_tuple_struct() {
#[derive(CheckBytes, Debug)]
#[bytecheck(crate)]
struct Test(u32, bool, CharLE);
let value = Test(42, true, 'x'.into());
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
unsafe {
// These tests assume the struct is packed (u32, char, bool)
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
42u8, 16u8, 20u8, 3u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x00u8, 0x00u8, 0x11u8, 0u8, 1u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 0u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 2u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
}
}
#[test]
fn test_struct() {
#[derive(CheckBytes, Debug)]
#[bytecheck(crate)]
struct Test {
a: u32,
b: bool,
c: CharLE,
}
let value = Test {
a: 42,
b: true,
c: 'x'.into(),
};
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
unsafe {
// These tests assume the struct is packed (u32, char, bool)
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
42u8, 16u8, 20u8, 3u8, 0x78u8, 0u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x00u8, 0xd8u8, 0u8, 0u8, 1u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x00u8, 0x00u8, 0x11u8, 0u8, 1u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 0u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 0x78u8, 0u8, 0u8, 0u8, 2u8, 255u8,
255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
}
}
#[test]
fn test_generic_struct() {
#[derive(CheckBytes, Debug)]
#[bytecheck(crate)]
struct Test<T> {
a: u32,
b: T,
}
let value = Test { a: 42, b: true };
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
unsafe {
check_bytes::<Test<bool>, Failure>(
bytes![0u8, 0u8, 0u8, 0u8, 1u8, 255u8, 255u8, 255u8].cast(),
)
.unwrap();
check_bytes::<Test<bool>, Failure>(
bytes![12u8, 34u8, 56u8, 78u8, 1u8, 255u8, 255u8, 255u8].cast(),
)
.unwrap();
check_bytes::<Test<bool>, Failure>(
bytes![0u8, 0u8, 0u8, 0u8, 0u8, 255u8, 255u8, 255u8].cast(),
)
.unwrap();
check_bytes::<Test<bool>, Failure>(
bytes![0u8, 0u8, 0u8, 0u8, 2u8, 255u8, 255u8, 255u8].cast(),
)
.unwrap_err();
}
}
#[test]
fn test_enum() {
#[allow(dead_code)]
#[derive(CheckBytes, Debug)]
#[bytecheck(crate)]
#[repr(u8)]
enum Test {
A(u32, bool, CharLE),
B { a: u32, b: bool, c: CharLE },
C,
}
let value = Test::A(42, true, 'x'.into());
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
let value = Test::B {
a: 42,
b: true,
c: 'x'.into(),
};
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
let value = Test::C;
unsafe {
check_bytes::<_, Failure>(&value).unwrap();
}
unsafe {
check_bytes::<Test, Failure>(
bytes![
0u8, 0u8, 0u8, 0u8, 12u8, 34u8, 56u8, 78u8, 1u8, 255u8,
255u8, 255u8, 120u8, 0u8, 0u8, 0u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
1u8, 0u8, 0u8, 0u8, 12u8, 34u8, 56u8, 78u8, 1u8, 255u8,
255u8, 255u8, 120u8, 0u8, 0u8, 0u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
2u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
255u8, 255u8, 255u8, 255u8, 25u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap();
check_bytes::<Test, Failure>(
bytes![
3u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8, 255u8,
255u8, 255u8, 255u8, 255u8, 25u8, 255u8, 255u8, 255u8,
]
.cast(),
)
.unwrap_err();
}
}
#[test]
fn test_explicit_enum_values() {
#[derive(CheckBytes, Debug)]
#[bytecheck(crate)]
#[repr(u8)]
enum Test {
A,
B = 100,
C,
D = 200,
E,
}
unsafe {
check_bytes::<_, Failure>(&Test::A).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&Test::B).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&Test::C).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&Test::D).unwrap();
}
unsafe {
check_bytes::<_, Failure>(&Test::E).unwrap();
}
unsafe {
check_bytes::<Test, Failure>(bytes![1u8].cast()).unwrap_err();
check_bytes::<Test, Failure>(bytes![99u8].cast()).unwrap_err();
check_bytes::<Test, Failure>(bytes![102u8].cast()).unwrap_err();
check_bytes::<Test, Failure>(bytes![199u8].cast()).unwrap_err();
check_bytes::<Test, Failure>(bytes![202u8].cast()).unwrap_err();
check_bytes::<Test, Failure>(bytes![255u8].cast()).unwrap_err();
}
}
#[test]
fn test_recursive() {
struct MyBox<T: ?Sized> {
inner: *const T,
}
unsafe impl<T, C> CheckBytes<C> for MyBox<T>
where
T: CheckBytes<C>,
C: Fallible + ?Sized,
{
unsafe fn check_bytes(
value: *const Self,
context: &mut C,
) -> Result<(), C::Error> {
unsafe { T::check_bytes((*value).inner, context) }
}
}
#[allow(dead_code)]
#[derive(CheckBytes)]
#[bytecheck(crate)]
#[repr(u8)]
enum Node {
Nil,
Cons(#[bytecheck(omit_bounds)] MyBox<Node>),
}
unsafe {
let nil = Node::Nil;
let cons = Node::Cons(MyBox {
inner: &nil as *const Node,
});
check_bytes::<Node, Failure>(&cons).unwrap();
}
}
#[test]
fn test_explicit_crate_root() {
mod bytecheck {}
mod m {
pub use crate as bc;
}
#[derive(CheckBytes)]
#[bytecheck(crate = m::bc)]
struct Test;
unsafe {
check_bytes::<_, Infallible>(&Test).unwrap();
}
#[derive(CheckBytes)]
#[bytecheck(crate = crate)]
struct Test2;
unsafe {
check_bytes::<_, Infallible>(&Test2).unwrap();
}
}
trait MyContext {
fn set_value(&mut self, value: i32);
}
impl<T: MyContext, E> MyContext for Strategy<T, E> {
fn set_value(&mut self, value: i32) {
T::set_value(self, value)
}
}
struct FooContext {
value: i32,
}
impl MyContext for FooContext {
fn set_value(&mut self, value: i32) {
self.value = value;
}
}
#[test]
fn test_derive_verify_unit_struct() {
unsafe impl<C: Fallible + MyContext + ?Sized> Verify<C> for UnitStruct {
fn verify(&self, context: &mut C) -> Result<(), C::Error> {
context.set_value(1);
Ok(())
}
}
#[derive(CheckBytes)]
#[bytecheck(crate, verify)]
struct UnitStruct;
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Infallible>(
&UnitStruct,
&mut context,
)
.unwrap();
}
assert_eq!(context.value, 1);
}
#[test]
fn test_derive_verify_struct() {
unsafe impl<C: Fallible + MyContext + ?Sized> Verify<C> for Struct {
fn verify(&self, context: &mut C) -> Result<(), C::Error> {
context.set_value(self.value);
Ok(())
}
}
#[derive(CheckBytes)]
#[bytecheck(crate, verify)]
struct Struct {
value: i32,
}
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Infallible>(
&Struct { value: 4 },
&mut context,
)
.unwrap();
}
assert_eq!(context.value, 4);
}
#[test]
fn test_derive_verify_tuple_struct() {
unsafe impl<C> Verify<C> for TupleStruct
where
C: Fallible + MyContext + ?Sized,
{
fn verify(&self, context: &mut C) -> Result<(), C::Error> {
context.set_value(self.0);
Ok(())
}
}
#[derive(CheckBytes)]
#[bytecheck(crate, verify)]
struct TupleStruct(i32);
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Infallible>(
&TupleStruct(10),
&mut context,
)
.unwrap();
}
assert_eq!(context.value, 10);
}
#[test]
fn test_derive_verify_enum() {
unsafe impl<C: Fallible + MyContext + ?Sized> Verify<C> for Enum {
fn verify(&self, context: &mut C) -> Result<(), C::Error> {
match self {
Enum::A => context.set_value(2),
Enum::B(value) => context.set_value(*value),
Enum::C { value } => context.set_value(*value),
}
Ok(())
}
}
#[derive(CheckBytes)]
#[bytecheck(crate, verify)]
#[repr(u8)]
enum Enum {
A,
B(i32),
C { value: i32 },
}
// Unit variant
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Failure>(&Enum::A, &mut context)
.unwrap();
}
assert_eq!(context.value, 2);
// Tuple variant
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Failure>(
&Enum::B(5),
&mut context,
)
.unwrap();
}
assert_eq!(context.value, 5);
// Struct variant
let mut context = FooContext { value: 0 };
unsafe {
check_bytes_with_context::<_, _, Failure>(
&Enum::C { value: 7 },
&mut context,
)
.unwrap();
}
assert_eq!(context.value, 7);
}
}