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
/*!
A documentation-only module for #\[deku\] attributes
# Scopes
To understand the `Scope` column of the table below:
```rust,ignore
#[deku(/* top-level */)]
struct DekuStruct {
#[deku( /* field */)]
field: u8,
}
#[deku(/* top-level */)]
enum DekuEnum {
#[deku(/* variant */)]
VariantA,
#[deku(/* variant */)]
VariantB( #[deku(/* field */)] u8 ),
#[deku(/* variant */)]
VariantC {
#[deku( /* field */)]
field: u8,
}
}
```
# List of attributes
| Attribute | Scope | Description
|-----------|------------------|------------
| [endian](#endian) | top-level, field | Set the endianness
| [magic](#magic) | top-level | A magic value that must be present at the start of this struct/enum
| [assert](#assert) | field | Assert a condition
| [assert_eq](#assert_eq) | field | Assert equals on the field
| [bits](#bits) | field | Set the bit-size of the field
| [bytes](#bytes) | field | Set the byte-size of the field
| [count](#count) | field | Set the field representing the element count of a container
| [bits_read](#bits_read) | field | Set the field representing the number of bits to read into a container
| [bytes_read](#bytes_read) | field | Set the field representing the number of bytes to read into a container
| [until](#until) | field | Set a predicate returning when to stop reading elements into a container
| [update](#update) | field | Apply code over the field when `.update()` is called
| [temp](#temp) | field | Read the field but exclude it from the struct/enum
| [skip](#skip) | field | Skip the reading/writing of a field
| [pad_bytes_before](#pad_bytes_before) | field | Skip bytes before reading, pad before writing
| [pad_bits_before](#pad_bits_before) | field | Skip bits before reading, pad before writing
| [pad_bytes_after](#pad_bytes_after) | field | Skip bytes after reading, pad after writing
| [pad_bits_after](#pad_bits_after) | field | Skip bits after reading, pad after writing
| [cond](#cond) | field | Conditional expression for the field
| [default](#default) | field | Provide default value. Used with [skip](#skip) or [cond](#cond)
| [map](#map) | field | Apply a function over the result of reading
| [reader](#readerwriter) | variant, field | Custom reader code
| [writer](#readerwriter) | variant, field | Custom writer code
| [ctx](#ctx) | top-level, field| Context list for context sensitive parsing
| [ctx_default](#ctx_default) | top-level, field| Default context values
| enum: [id](#id) | top-level, variant | enum or variant id value
| enum: [id_pat](#id_pat) | variant | variant id match pattern
| enum: [type](#type) | top-level | Set the type of the variant `id`
| enum: [bits](#bits-1) | top-level | Set the bit-size of the variant `id`
| enum: [bytes](#bytes-1) | top-level | Set the byte-size of the variant `id`
# endian
Set to read/write bytes in a specific byte order.
Values: `big`, `little` or an expression which returns a [`Endian`](super::ctx::Endian)
Precedence: field > top-level > system endianness (default)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
// #[deku(endian = "little")] // top-level, defaults to system endianness
struct DekuTest {
#[deku(endian = "big")] // field-level override
field_be: u16,
field_default: u16, // defaults to top-level
}
let data: Vec<u8> = vec![0xAB, 0xCD, 0xAB, 0xCD];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_be: 0xABCD,
field_default: 0xCDAB,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
**Note**: The `endian` is passed as a context argument to sub-types
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
#[deku(endian = "endian", ctx = "endian: deku::ctx::Endian")] // context passed from `DekuTest` top-level endian
struct Child {
field_a: u16
}
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
#[deku(endian = "little")] // top-level, defaults to system endianness
struct DekuTest {
#[deku(endian = "big")] // field-level override
field_be: u16,
field_default: u16, // defaults to top-level
// because a top-level endian is specified,
// it is passed as a context
field_child: Child,
}
let data: Vec<u8> = vec![0xAB, 0xCD, 0xAB, 0xCD, 0xEF, 0xBE];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_be: 0xABCD,
field_default: 0xCDAB,
field_child: Child { field_a: 0xBEEF }
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# magic
Sets a "magic" value that must be present in the data at the start of
a struct/enum when reading, and that is written out of the start of
that type's data when writing.
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
#[deku(magic = b"deku")]
struct DekuTest {
data: u8
}
let data: Vec<u8> = vec![b'd', b'e', b'k', b'u', 50];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { data: 50 },
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# assert
Assert a condition after reading and before writing a field
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(assert = "*data >= 8")]
data: u8
}
let data: Vec<u8> = vec![0x00, 0x01, 0x02];
let value = DekuTest::try_from(data.as_ref());
assert_eq!(
Err(DekuError::Assertion("DekuTest.data field failed assertion: * data >= 8".into())),
value
);
```
# assert_eq
Assert equals after reading and before writing a field
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(assert_eq = "0x01")]
data: u8,
}
let data: Vec<u8> = vec![0x01];
let mut value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { data: 0x01 },
value
);
value.data = 0x02;
let value: Result<Vec<u8>, DekuError> = value.try_into();
assert_eq!(
Err(DekuError::Assertion("DekuTest.data field failed assertion: data == 0x01".into())),
value
);
```
# bits
Set the bit-size of the field
**Note**: Cannot be used in combination with [bytes](#bytes)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(bits = 2)]
field_a: u8,
#[deku(bits = 6)]
field_b: u8,
field_c: u8, // defaults to size_of<u8>*8
}
let data: Vec<u8> = vec![0b11_101010, 0xFF];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0b11,
field_b: 0b101010,
field_c: 0xFF,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# bytes
Set the byte-size of the field
**Note**: Cannot be used in combination with [bits](#bits)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(bytes = 2)]
field_a: u32,
field_b: u8, // defaults to size_of<u8>
}
let data: Vec<u8> = vec![0xAB, 0xCD, 0xFF];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0xCDAB,
field_b: 0xFF,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# count
Specify the field representing the length of the container, i.e. a Vec
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(update = "self.items.len()")]
count: u8,
#[deku(count = "count")]
items: Vec<u8>,
}
let data: Vec<u8> = vec![0x02, 0xAB, 0xCD];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
count: 0x02,
items: vec![0xAB, 0xCD],
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
**Note**: See [update](#update) for more information on the attribute!
# bytes_read
Specify the field representing the total number of bytes to read into a container
See the following example, where `InnerDekuTest` is 2 bytes, so setting `bytes_read` to
4 will read 2 items into the container:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct InnerDekuTest {
field_a: u8,
field_b: u8
}
# #[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(update = "(self.items.len() / 2)")]
bytes: u8,
#[deku(bytes_read = "bytes")]
items: Vec<InnerDekuTest>,
}
let data: Vec<u8> = vec![0x04, 0xAB, 0xBC, 0xDE, 0xEF];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
bytes: 0x04,
items: vec![
InnerDekuTest{field_a: 0xAB, field_b: 0xBC},
InnerDekuTest{field_a: 0xDE, field_b: 0xEF}],
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
**Note**: See [update](#update) for more information on the attribute!
# bits_read
This is equivalent to [bytes_read](#bytes_read), however specifies the bit limit instead
of a byte limit
# until
Specifies a predicate which sets when to stop reading values into the container.
**Note**: The last value which matches the predicate is read
The predicate is given a borrow to each item as it is read, and must return a boolean
as to whether this should be the last item or not. If it returns true, then reading stops.
A good example of this is to read a null-terminated string:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# use std::ffi::CString;
# #[derive(Debug, PartialEq, DekuRead)]
struct DekuTest {
#[deku(until = "|v: &u8| *v == 0")]
string: Vec<u8>
}
let data: Vec<u8> = vec![b'H', b'e', b'l', b'l', b'o', 0];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
string: CString::new(b"Hello".to_vec()).unwrap().into_bytes_with_nul()
},
value
);
```
# update
Specify custom code to run on the field when `.update()` is called on the struct/enum
Example:
```rust
use deku::prelude::*;
use std::convert::{TryInto, TryFrom};
#[derive(Debug, PartialEq, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(update = "self.items.len()")]
count: u8,
#[deku(count = "count")]
items: Vec<u8>,
}
let data: Vec<u8> = vec![0x02, 0xAB, 0xCD];
// `mut` so it can be updated
let mut value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { count: 0x02, items: vec![0xAB, 0xCD] },
value
);
// push a new item to the vec
value.items.push(0xFF);
// update it, this will update the `count` field
value.update().unwrap();
assert_eq!(
DekuTest { count: 0x03, items: vec![0xAB, 0xCD, 0xFF] },
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x03, 0xAB, 0xCD, 0xFF], value);
```
# temp
A temporary field
Included in the reading of the struct/enum but not stored
**Note**: Struct/enum must be derived with `#[deku_derive(...)]` to derive
`DekuRead` and/or `DekuWrite`, not with `#[derive(...)]`. This is because the
struct/enum needs to be modified at compile time.
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[deku_derive(DekuRead, DekuWrite)]
#[derive(Debug, PartialEq)]
struct DekuTest {
#[deku(temp)]
num_items: u8,
#[deku(count = "num_items", endian = "big")]
items: Vec<u16>,
}
let data: Vec<u8> = vec![0x01, 0xBE, 0xEF];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
items: vec![0xBEEF]
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0xBE, 0xEF], value);
```
# skip
Skip the reading/writing of a field.
Defaults value to [default](#default)
**Note**: Can be paired with [cond](#cond) to have conditional skipping
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
field_a: u8,
#[deku(skip)]
field_b: Option<u8>,
field_c: u8,
}
let data: Vec<u8> = vec![0x01, 0x02];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { field_a: 0x01, field_b: None, field_c: 0x02 },
value
);
```
# pad_bytes_before
Skip a number of bytes before reading, pad with 0x00s before writing
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
pub struct DekuTest {
pub field_a: u8,
#[deku(pad_bytes_before = "2")]
pub field_b: u8,
}
let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0xAA,
field_b: 0xDD,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0xAA, 0x00, 0x00, 0xDD], value);
```
# pad_bits_before
Skip a number of bytes before reading, pad with 0s before writing
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(bits = 2)]
field_a: u8,
#[deku(pad_bits_before = "2", bits = 4)]
field_b: u8,
}
let data: Vec<u8> = vec![0b10_01_1001];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0b10,
field_b: 0b1001,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0b10_00_1001], value);
```
# pad_bytes_after
Skip a number of bytes after reading, pad with 0x00s after writing
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
pub struct DekuTest {
#[deku(pad_bytes_after = "2")]
pub field_a: u8,
pub field_b: u8,
}
let data: Vec<u8> = vec![0xAA, 0xBB, 0xCC, 0xDD];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0xAA,
field_b: 0xDD,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0xAA, 0x00, 0x00, 0xDD], value);
```
# pad_bits_after
Skip a number of bytes after reading, pad with 0s after writing
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(bits = 2, pad_bits_after = "2")]
field_a: u8,
#[deku(bits = 4)]
field_b: u8,
}
let data: Vec<u8> = vec![0b10_01_1001];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
field_a: 0b10,
field_b: 0b1001,
},
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0b10_00_1001], value);
```
# cond
Specify a condition to parse or skip a field
**Note**: Can be paired with [default](#default)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
field_a: u8,
#[deku(cond = "*field_a == 0x01")]
field_b: Option<u8>,
#[deku(cond = "*field_b == Some(0xFF)", default = "Some(0x05)")]
field_c: Option<u8>,
#[deku(skip, cond = "*field_a == 0x01", default = "Some(0x06)")]
field_d: Option<u8>,
}
let data: Vec<u8> = vec![0x01, 0x02];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { field_a: 0x01, field_b: Some(0x02), field_c: Some(0x05), field_d: Some(0x06)},
value
);
assert_eq!(
vec![0x01, 0x02, 0x05],
value.to_bytes().unwrap(),
)
```
# default
Default code tokens used with [skip](#skip) or [cond](#cond)
Defaults to `Default::default()`
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
field_a: u8,
#[deku(skip, default = "Some(*field_a)")]
field_b: Option<u8>,
field_c: u8,
}
let data: Vec<u8> = vec![0x01, 0x02];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { field_a: 0x01, field_b: Some(0x01), field_c: 0x02 },
value
);
```
# map
Specify a function or lambda to apply to the result of the read
Example:
Read a `u8` and apply a function to convert it to a `String`.
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead)]
struct DekuTest {
#[deku(map = "|field: u8| -> Result<_, DekuError> { Ok(field.to_string()) }")]
field_a: String,
#[deku(map = "DekuTest::map_field_b")]
field_b: String,
}
impl DekuTest {
fn map_field_b(field_b: u8) -> Result<String, DekuError> {
Ok(field_b.to_string())
}
}
let data: Vec<u8> = vec![0x01, 0x02];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { field_a: "1".to_string(), field_b: "2".to_string() },
value
);
```
# reader/writer
Specify custom reader or writer tokens for reading a field or variant
Example:
```rust
use std::convert::{TryInto, TryFrom};
use deku::bitvec::{BitSlice, BitVec, Msb0};
use deku::prelude::*;
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
#[deku(
reader = "DekuTest::read(deku::rest)",
writer = "DekuTest::write(deku::output, &self.field_a)"
)]
field_a: String,
}
impl DekuTest {
/// Read and convert to String
fn read(
rest: &BitSlice<u8, Msb0>,
) -> Result<(&BitSlice<u8, Msb0>, String), DekuError> {
let (rest, value) = u8::read(rest, ())?;
Ok((rest, value.to_string()))
}
/// Parse from String to u8 and write
fn write(output: &mut BitVec<u8, Msb0>, field_a: &str) -> Result<(), DekuError> {
let value = field_a.parse::<u8>().unwrap();
value.write(output, ())
}
}
let data: Vec<u8> = vec![0x01];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest { field_a: "1".to_string() },
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# ctx
This attribute allows sending and receiving context (variables/values) to sub-parsers/writers
**Note**: `endian`, `bytes`, `bits`, `count` attributes use `ctx` internally, see examples below
**top-level**: The value of a ctx attribute is a function argument list,
for example `#[deku(ctx = "a: u8, b: String")]`
**field-level**: The value of the ctx attribute is a list of expressions,
for example `#[deku("a, b")]`
**Visibility**: The following can be accessed:
1. All former fields which have been parsed (given as a reference).
2. `endian`, `bytes`, `bits` attributes declared on the top-level
- These are prepended to the list of ctx variables
Example
```rust
# use deku::prelude::*;
#[derive(DekuRead, DekuWrite)]
#[deku(ctx = "a: u8")]
struct Subtype {
#[deku(map = "|b: u8| -> Result<_, DekuError> { Ok(b + a) }")]
b: u8
}
#[derive(DekuRead, DekuWrite)]
struct Test {
a: u8,
#[deku(ctx = "*a")] // pass `a` to `SubType`, `a` is a reference
sub: Subtype
}
let data: Vec<u8> = vec![0x01, 0x02];
let (rest, value) = Test::from_bytes((&data[..], 0)).unwrap();
assert_eq!(value.a, 0x01);
assert_eq!(value.sub.b, 0x01 + 0x02)
```
**Note**: In addition, `endian`, `bytes` and `bits` use the `ctx` concept internally, examples below are equivalent:
Example:
```ignore
struct Type1 {
#[deku(endian = "big", bits = "1")]
field: u8,
}
// is equivalent to
struct Type1 {
#[deku(ctx = "Endian::Big, BitSize(1)")]
field: u8,
}
```
Example: Adding context
```ignore
#[deku(endian = "big")]
struct Type1 {
field_a: u16,
#[deku(bits = "5", ctx = "*field_a")]
field_b: SubType,
}
// is equivalent to
struct Type1 {
#[deku(ctx = "Endian::Big")]
field_a: u16,
#[deku(ctx = "Endian::Big, BitSize(5), *field_a")] // endian is prepended
field_b: SubType,
}
```
# ctx_default
When paired with the [`ctx`](#ctx) attribute, `ctx_default` provides default
values for the context
Example:
```rust
# use deku::prelude::*;
#[derive(DekuRead, DekuWrite)]
#[deku(ctx = "a: u8", ctx_default = "1")] // Defaults `a` to 1
struct Subtype {
#[deku(map = "|b: u8| -> Result<_, DekuError> { Ok(b + a) }")]
b: u8
}
#[derive(DekuRead, DekuWrite)]
struct Test {
a: u8,
#[deku(ctx = "*a")] // pass `a` to `SubType`, `a` is a reference
sub: Subtype
}
let data: Vec<u8> = vec![0x01, 0x02];
// Use with context from `Test`
let (rest, value) = Test::from_bytes((&data[..], 0)).unwrap();
assert_eq!(value.a, 0x01);
assert_eq!(value.sub.b, 0x01 + 0x02);
// Use as a stand-alone container, using defaults
// Note: `from_bytes` is now available on `SubType`
let data: Vec<u8> = vec![0x02];
let (rest, value) = Subtype::from_bytes((&data[..], 0)).unwrap();
assert_eq!(value.b, 0x01 + 0x02)
```
# id
## id (top-level)
Specify the enum id
This is useful in cases when the enum `id` is already consumed or is given externally
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
struct DekuTest {
my_id: u8,
data: u8,
#[deku(ctx = "*my_id")]
enum_from_id: MyEnum,
}
#[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(ctx = "my_id: u8", id = "my_id")]
enum MyEnum {
#[deku(id = "1")]
VariantA(u8),
#[deku(id = "2")]
VariantB,
}
let data: Vec<u8> = vec![0x01_u8, 0xff, 0xab];
let ret_read = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest {
my_id: 0x01,
data: 0xff,
enum_from_id: MyEnum::VariantA(0xab),
},
ret_read
);
let ret_write: Vec<u8> = ret_read.try_into().unwrap();
assert_eq!(ret_write, data)
```
## id (variant)
Specify the identifier of the enum variant, must be paired with [type](#type)
or [id (top-level)](#id-top-level)
**Note**:
- If no `id` is specified, it is defaulted to the discriminant value.
- The discriminant value is retreived using the `as` keyword.
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(type = "u8")]
enum DekuTest {
#[deku(id = "0x01")]
VariantA(u8),
#[deku(id = "0x02")]
VariantB(u8, u16),
}
let data: Vec<u8> = vec![0x01, 0xFF, 0x02, 0xAB, 0xEF, 0xBE];
let (rest, value) = DekuTest::from_bytes((data.as_ref(), 0)).unwrap();
assert_eq!(
DekuTest::VariantA(0xFF),
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x01, 0xFF], variant_bytes);
let (rest, value) = DekuTest::from_bytes(rest).unwrap();
assert_eq!(
DekuTest::VariantB(0xAB, 0xBEEF),
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x02, 0xAB, 0xEF, 0xBE], variant_bytes);
```
Example discriminant
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(type = "u8")]
enum DekuTest {
VariantA = 0x01,
VariantB,
}
let data: Vec<u8> = vec![0x01, 0x02];
let (rest, value) = DekuTest::from_bytes((data.as_ref(), 0)).unwrap();
assert_eq!(
DekuTest::VariantA,
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x01], variant_bytes);
let (rest, value) = DekuTest::from_bytes(rest).unwrap();
assert_eq!(
DekuTest::VariantB,
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x02], variant_bytes);
```
# id_pat
Specify the identifier in the form of a match pattern for the enum variant.
The enum variant must have space to store the identifier for proper writing.
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(type = "u8")]
enum DekuTest {
#[deku(id = "0x01")]
VariantA(u8),
#[deku(id_pat = "0x02..=0x06")]
VariantB {
id: u8
},
#[deku(id_pat = "_")]
VariantC(u8),
}
let data: Vec<u8> = vec![0x03, 0xFF];
let (rest, value) = DekuTest::from_bytes((data.as_ref(), 0)).unwrap();
assert_eq!(
DekuTest::VariantB { id: 0x03 },
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0x03], variant_bytes);
let (rest, value) = DekuTest::from_bytes(rest).unwrap();
assert_eq!(
DekuTest::VariantC(0xFF),
value
);
let variant_bytes: Vec<u8> = value.try_into().unwrap();
assert_eq!(vec![0xFF], variant_bytes);
```
# type
Specify the type of the enum variant id to consume, see [example](#id-variant)
# bits
Set the bit size of the enum variant `id`
**Note**: Cannot be used in combination with [bytes](#bytes)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(type = "u8", bits = "4")]
enum DekuTest {
#[deku(id = "0b1001")]
VariantA( #[deku(bits = "4")] u8, u8),
}
let data: Vec<u8> = vec![0b1001_0110, 0xFF];
let (rest, value) = DekuTest::from_bytes((&data, 0)).unwrap();
assert_eq!(
DekuTest::VariantA(0b0110, 0xFF),
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
# bytes
Set the byte size of the enum variant `id`
**Note**: Cannot be used in combination with [bits](#bits)
Example:
```rust
# use deku::prelude::*;
# use std::convert::{TryInto, TryFrom};
# #[derive(PartialEq, Debug, DekuRead, DekuWrite)]
#[deku(type = "u32", bytes = "2")]
enum DekuTest {
#[deku(id = "0xBEEF")]
VariantA(u8),
}
let data: Vec<u8> = vec![0xEF, 0xBE, 0xFF];
let value = DekuTest::try_from(data.as_ref()).unwrap();
assert_eq!(
DekuTest::VariantA(0xFF),
value
);
let value: Vec<u8> = value.try_into().unwrap();
assert_eq!(data, value);
```
*/