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
use anyhow::{bail, Context, Result};

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum OpcodeClass {
    Load,         // non-standard load
    LoadReg,      // load into register
    Store,        // store from immediate
    StoreReg,     // store from register
    Arithmetic,   // 32-bit arithmetic
    Jump,         // 64-bit jumps
    Jump32,       // 32-bit jumps
    Arithmetic64, // 64-bit arithmetic
}

impl OpcodeClass {
    const MASK: u64 = 0x07;
    const LOAD: u8 = 0x00;
    const LOAD_REG: u8 = 0x01;
    const STORE: u8 = 0x02;
    const STORE_REG: u8 = 0x03;
    const ARITHMETIC: u8 = 0x04;
    const JUMP: u8 = 0x05;
    const JUMP32: u8 = 0x06;
    const ARITHMETIC64: u8 = 0x07;

    fn from_raw(instruction: u64) -> Self {
        let class = (instruction & Self::MASK) as u8;
        match class {
            Self::LOAD => Self::Load,
            Self::LOAD_REG => Self::LoadReg,
            Self::STORE => Self::Store,
            Self::STORE_REG => Self::StoreReg,
            Self::ARITHMETIC => Self::Arithmetic,
            Self::JUMP => Self::Jump,
            Self::JUMP32 => Self::Jump32,
            Self::ARITHMETIC64 => Self::Arithmetic64,
            _ => panic!("Opcode class match arms have been broken"),
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Load => Self::LOAD,
            Self::LoadReg => Self::LOAD_REG,
            Self::Store => Self::STORE,
            Self::StoreReg => Self::STORE_REG,
            Self::Arithmetic => Self::ARITHMETIC,
            Self::Jump => Self::JUMP,
            Self::Jump32 => Self::JUMP32,
            Self::Arithmetic64 => Self::ARITHMETIC64,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum SourceOperand {
    Immediate, // use immediate for jump/arithmetic
    Register,  // use source register for jump/arithmetic
}

impl SourceOperand {
    const MASK: u64 = 0x08;
    const IMMEDIATE: u8 = 0x00;
    const REGISTER: u8 = 0x08;

    fn from_raw(instruction: u64) -> Self {
        if instruction & Self::MASK == Self::MASK {
            Self::Register
        } else {
            Self::Immediate
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Register => Self::REGISTER,
            Self::Immediate => Self::IMMEDIATE,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ArithmeticOperation {
    Add, // dst += src
    Sub, // dst -= src
    Mul, // dst *= src
    Div, // dst /= src
    Or,  // dst |= src
    And, // dst &= src
    Lhs, // dst <<= src
    Rhs, // dst >>= src
    Neg, // dst = ~src
    Mod, // dst %= src
    Xor, // dst ^= src
    Mov, // dst = src
    Ash, // dst s>> src
    End, // dst = swap(dst)
}

impl ArithmeticOperation {
    const MASK: u64 = 0xf0;
    const ADD: u8 = 0x00; // dst += src
    const SUB: u8 = 0x10; // dst -= src
    const MUL: u8 = 0x20; // dst *= src
    const DIV: u8 = 0x30; // dst /= src
    const OR: u8 = 0x40; // dst |= src
    const AND: u8 = 0x50; // dst &= src
    const LHS: u8 = 0x60; // dst <<= src
    const RHS: u8 = 0x70; // dst >>= src
    const NEG: u8 = 0x80; // dst: u8 = ~src
    const MOD: u8 = 0x90; // dst %= src
    const XOR: u8 = 0xa0; // dst ^= src
    const MOV: u8 = 0xb0; // dst: u8 = src
    const ASH: u8 = 0xc0; // dst s>> src
    const END: u8 = 0xd0; // dst: u8 = swap(dst)

    fn from_raw(instruction: u64) -> Option<Self> {
        let operation = (instruction & Self::MASK) as u8;
        match operation {
            Self::ADD => Some(Self::Add),
            Self::SUB => Some(Self::Sub),
            Self::MUL => Some(Self::Mul),
            Self::DIV => Some(Self::Div),
            Self::OR => Some(Self::Or),
            Self::AND => Some(Self::And),
            Self::LHS => Some(Self::Lhs),
            Self::RHS => Some(Self::Rhs),
            Self::NEG => Some(Self::Neg),
            Self::MOD => Some(Self::Mod),
            Self::XOR => Some(Self::Xor),
            Self::MOV => Some(Self::Mov),
            Self::ASH => Some(Self::Ash),
            Self::END => Some(Self::End),
            _ => None,
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Add => Self::ADD,
            Self::Sub => Self::SUB,
            Self::Mul => Self::MUL,
            Self::Div => Self::DIV,
            Self::Or => Self::OR,
            Self::And => Self::AND,
            Self::Lhs => Self::LHS,
            Self::Rhs => Self::RHS,
            Self::Neg => Self::NEG,
            Self::Mod => Self::MOD,
            Self::Xor => Self::XOR,
            Self::Mov => Self::MOV,
            Self::Ash => Self::ASH,
            Self::End => Self::END,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum SwapOrder {
    #[default]
    Little = 0x00,
    Big = 0x08,
}

impl SwapOrder {
    const MASK: u64 = 0x08;
    const LITTLE: u8 = 0x00;
    const BIG: u8 = 0x08;

    fn from_raw(instruction: u64) -> Self {
        if instruction & Self::MASK == Self::MASK {
            Self::Big
        } else {
            Self::Little
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Big => Self::BIG,
            Self::Little => Self::LITTLE,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ArithmeticInstruction {
    class: OpcodeClass,
    source: SourceOperand,
    operation: ArithmeticOperation,
    order: SwapOrder,
}

impl ArithmeticInstruction {
    fn from_raw(instruction: u64) -> Result<Self> {
        let class = OpcodeClass::from_raw(instruction);
        match class {
            OpcodeClass::Arithmetic | OpcodeClass::Arithmetic64 => (),
            _ => bail!("Tried to decode arithmetic instruction for non-arithmetic class"),
        }

        Ok(Self {
            class,
            source: SourceOperand::from_raw(instruction),
            operation: ArithmeticOperation::from_raw(instruction)
                .context("Invalid arithmetic operation")?,
            order: SwapOrder::from_raw(instruction),
        })
    }

    fn opcode(&self) -> u8 {
        self.class.opcode() | self.source.opcode() | self.operation.opcode() | self.order.opcode()
    }

    /// Returns the opcode's class.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, OpcodeClass, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R1, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Arithmetic(_)));
    /// if let Opcode::Arithmetic(arithmetic) = opcode {
    ///     assert!(matches!(arithmetic.get_class(), OpcodeClass::Arithmetic64));
    /// }
    /// ```
    pub fn get_class(&self) -> &OpcodeClass {
        &self.class
    }

    /// Returns the opcode's source operand.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, Register, SourceOperand};
    ///
    /// let instruction = Instruction::addx64(Register::R1, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Arithmetic(_)));
    /// if let Opcode::Arithmetic(arithmetic) = opcode {
    ///     assert!(matches!(arithmetic.get_source(), SourceOperand::Register));
    /// }
    /// ```
    pub fn get_source(&self) -> &SourceOperand {
        &self.source
    }

    /// Returns the arithmetic operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Opcode, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R1, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Arithmetic(_)));
    /// if let Opcode::Arithmetic(arithmetic) = opcode {
    ///     assert!(matches!(arithmetic.get_operation(), ArithmeticOperation::Add));
    /// }
    /// ```
    pub fn get_operation(&self) -> &ArithmeticOperation {
        &self.operation
    }

    /// Returns the operation's swap order, if the operation is ArithmeticOperation::End.
    pub fn get_order(&self) -> &SwapOrder {
        &self.order
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum JumpOperation {
    Absolute,
    IfEqual,
    IfGreater,
    IfGreaterOrEqual,
    IfAnd,
    IfNotEqual,
    IfSignedGreater,
    IfSignedGreaterOrEqual,
    Call,
    Exit,
    IfLessThan,
    IfLessThanOrEqual,
    IfSignedLessThan,
    IfSignedLessThanOrEqual,
}

impl JumpOperation {
    const MASK: u64 = 0xf0;
    const ABS: u8 = 0x00;
    const EQ: u8 = 0x10;
    const GT: u8 = 0x20;
    const GTE: u8 = 0x30;
    const AND: u8 = 0x40;
    const NEQ: u8 = 0x50;
    const SGT: u8 = 0x60;
    const SGTE: u8 = 0x70;
    const CALL: u8 = 0x80;
    const EXIT: u8 = 0x90;
    const LT: u8 = 0xa0;
    const LTE: u8 = 0xb0;
    const SLT: u8 = 0xc0;
    const SLTE: u8 = 0xd0;

    fn from_raw(instruction: u64) -> Option<Self> {
        let operation = (instruction & Self::MASK) as u8;
        match operation {
            Self::ABS => Some(Self::Absolute),
            Self::EQ => Some(Self::IfEqual),
            Self::GT => Some(Self::IfGreater),
            Self::GTE => Some(Self::IfGreaterOrEqual),
            Self::AND => Some(Self::IfAnd),
            Self::NEQ => Some(Self::IfNotEqual),
            Self::SGT => Some(Self::IfSignedGreater),
            Self::SGTE => Some(Self::IfSignedGreaterOrEqual),
            Self::CALL => Some(Self::Call),
            Self::EXIT => Some(Self::Exit),
            Self::LT => Some(Self::IfLessThan),
            Self::LTE => Some(Self::IfLessThanOrEqual),
            Self::SLT => Some(Self::IfSignedLessThan),
            Self::SLTE => Some(Self::IfSignedLessThanOrEqual),
            _ => None,
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Absolute => Self::ABS,
            Self::IfEqual => Self::EQ,
            Self::IfGreater => Self::GT,
            Self::IfGreaterOrEqual => Self::GTE,
            Self::IfAnd => Self::AND,
            Self::IfNotEqual => Self::NEQ,
            Self::IfSignedGreater => Self::SGT,
            Self::IfSignedGreaterOrEqual => Self::SGTE,
            Self::Call => Self::CALL,
            Self::Exit => Self::EXIT,
            Self::IfLessThan => Self::LT,
            Self::IfLessThanOrEqual => Self::LTE,
            Self::IfSignedLessThan => Self::SLT,
            Self::IfSignedLessThanOrEqual => Self::SLTE,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct JumpInstruction {
    class: OpcodeClass,
    source: SourceOperand,
    operation: JumpOperation,
}

impl JumpInstruction {
    fn from_raw(instruction: u64) -> Result<Self> {
        let class = OpcodeClass::from_raw(instruction);
        match class {
            OpcodeClass::Jump | OpcodeClass::Jump32 => (),
            _ => bail!("Tried to decode jump instruction for non-jump class"),
        }

        Ok(Self {
            class,
            source: SourceOperand::from_raw(instruction),
            operation: JumpOperation::from_raw(instruction).context("Invalid jump operation")?,
        })
    }

    fn opcode(&self) -> u8 {
        self.class.opcode() | self.source.opcode() | self.operation.opcode()
    }

    /// Returns the opcode's class.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, OpcodeClass, Register};
    ///
    /// let instruction = Instruction::exit();
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Jump(_)));
    /// if let Opcode::Jump(jump) = opcode {
    ///     assert!(matches!(jump.get_class(), OpcodeClass::Jump));
    /// }
    /// ```
    pub fn get_class(&self) -> &OpcodeClass {
        &self.class
    }

    /// Returns the opcode's source operand.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, Register, SourceOperand};
    ///
    /// let instruction = Instruction::exit();
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Jump(_)));
    /// if let Opcode::Jump(jump) = opcode {
    ///     assert!(matches!(jump.get_source(), SourceOperand::Immediate));
    /// }
    /// ```
    pub fn get_source(&self) -> &SourceOperand {
        &self.source
    }

    /// Returns the jump operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, JumpOperation, Opcode, Register};
    ///
    /// let instruction = Instruction::exit();
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Jump(_)));
    /// if let Opcode::Jump(jump) = opcode {
    ///     assert!(matches!(jump.get_operation(), JumpOperation::Exit));
    /// }
    /// ```
    pub fn get_operation(&self) -> &JumpOperation {
        &self.operation
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MemoryOpSize {
    Word,
    HalfWord,
    Byte,
    DoubleWord,
}

impl MemoryOpSize {
    const MASK: u64 = 0x18;
    const WORD: u8 = 0x00;
    const HALF_WORD: u8 = 0x08;
    const BYTE: u8 = 0x10;
    const DOUBLE_WORD: u8 = 0x18;

    fn from_raw(instruction: u64) -> Option<Self> {
        let size = (instruction & Self::MASK) as u8;
        match size {
            Self::WORD => Some(Self::Word),
            Self::HALF_WORD => Some(Self::HalfWord),
            Self::BYTE => Some(Self::Byte),
            Self::DOUBLE_WORD => Some(Self::DoubleWord),
            _ => None,
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Word => Self::WORD,
            Self::HalfWord => Self::HALF_WORD,
            Self::Byte => Self::BYTE,
            Self::DoubleWord => Self::DOUBLE_WORD,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MemoryOpMode {
    Immediate,
    Memory,
    Atomic,
}

impl MemoryOpMode {
    const MASK: u64 = 0xe0;
    const IMMEDIATE: u8 = 0x00;
    const MEMORY: u8 = 0x60;
    const ATOMIC: u8 = 0xc0;

    fn from_raw(instruction: u64) -> Option<Self> {
        let mode = (instruction & Self::MASK) as u8;
        match mode {
            Self::IMMEDIATE => Some(Self::Immediate),
            Self::MEMORY => Some(Self::Memory),
            Self::ATOMIC => Some(Self::Atomic),
            _ => None,
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Immediate => Self::IMMEDIATE,
            Self::Memory => Self::MEMORY,
            Self::Atomic => Self::ATOMIC,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MemoryOpLoadType {
    Void,
    Map,
    MapValue,
    BtfId,
    Function,
    MapIndex,
    MapIndexValue,
}

impl MemoryOpLoadType {
    const fn register_identifier(&self) -> Register {
        match self {
            Self::Void => Register::R0,
            Self::Map => Register::R1,
            Self::MapValue => Register::R2,
            Self::BtfId => Register::R3,
            Self::Function => Register::R4,
            Self::MapIndex => Register::R5,
            Self::MapIndexValue => Register::R6,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct MemoryInstruction {
    class: OpcodeClass,
    size: MemoryOpSize,
    mode: MemoryOpMode,
}

impl MemoryInstruction {
    fn from_raw(instruction: u64) -> Result<Self> {
        let class = OpcodeClass::from_raw(instruction);
        match class {
            OpcodeClass::Load
            | OpcodeClass::LoadReg
            | OpcodeClass::Store
            | OpcodeClass::StoreReg => (),
            _ => bail!("Tried to decode memory instruction for non-memory class"),
        }

        Ok(Self {
            class,
            size: MemoryOpSize::from_raw(instruction).context("Invalid memory operations size")?,
            mode: MemoryOpMode::from_raw(instruction).context("Invalid memory operation mode")?,
        })
    }

    fn opcode(&self) -> u8 {
        self.class.opcode() | self.size.opcode() | self.mode.opcode()
    }

    /// Returns the opcode's class.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, OpcodeClass, Register};
    ///
    /// let instruction = Instruction::storex64(Register::R1, 0, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Memory(_)));
    /// if let Opcode::Memory(memory) = opcode {
    ///     assert!(matches!(memory.get_class(), OpcodeClass::StoreReg));
    /// }
    /// ```
    pub fn get_class(&self) -> &OpcodeClass {
        &self.class
    }

    /// Returns the memory operation size.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Opcode, Register};
    ///
    /// let instruction = Instruction::storex64(Register::R1, 0, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Memory(_)));
    /// if let Opcode::Memory(memory) = opcode {
    ///     assert!(matches!(memory.get_size(), MemoryOpSize::DoubleWord));
    /// }
    /// ```
    pub fn get_size(&self) -> &MemoryOpSize {
        &self.size
    }

    /// Returns the memory operation mode.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpMode, Opcode, Register};
    ///
    /// let instruction = Instruction::storex64(Register::R1, 0, Register::R2);
    /// let opcode = instruction.get_opcode();
    /// assert!(matches!(opcode, Opcode::Memory(_)));
    /// if let Opcode::Memory(memory) = opcode {
    ///     assert!(matches!(memory.get_mode(), MemoryOpMode::Memory));
    /// }
    /// ```
    pub fn get_mode(&self) -> &MemoryOpMode {
        &self.mode
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum Register {
    #[default]
    R0,
    R1,
    R2,
    R3,
    R4,
    R5,
    R6,
    R7,
    R8,
    R9,
    R10,
}

impl Register {
    /// Returns a register that corresponds to the given integer.
    ///
    /// # Arguments
    ///
    /// * `n` - The integer representing the register.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// assert_eq!(Register::from_num(5).unwrap(), Register::R5)
    /// ```
    pub fn from_num(n: u8) -> Option<Self> {
        match n {
            0 => Some(Self::R0),
            1 => Some(Self::R1),
            2 => Some(Self::R2),
            3 => Some(Self::R3),
            4 => Some(Self::R4),
            5 => Some(Self::R5),
            6 => Some(Self::R6),
            7 => Some(Self::R7),
            8 => Some(Self::R8),
            9 => Some(Self::R9),
            10 => Some(Self::R10),
            _ => None,
        }
    }

    /// Returns the integer representation of a register.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::Register;
    ///
    /// let register = Register::R5;
    /// assert_eq!(register.as_num(), 5)
    /// ```
    pub fn as_num(&self) -> u8 {
        match self {
            Self::R0 => 0,
            Self::R1 => 1,
            Self::R2 => 2,
            Self::R3 => 3,
            Self::R4 => 4,
            Self::R5 => 5,
            Self::R6 => 6,
            Self::R7 => 7,
            Self::R8 => 8,
            Self::R9 => 9,
            Self::R10 => 10,
        }
    }

    /// Returns the string representation of a register.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{MemoryOpSize, Register};
    ///
    /// let register = Register::R5;
    /// assert_eq!(register.as_str(MemoryOpSize::DoubleWord), "r5")
    /// ```
    pub fn as_str(&self, size: MemoryOpSize) -> &'static str {
        match (self, size) {
            (Self::R0, MemoryOpSize::Byte) => "b0",
            (Self::R1, MemoryOpSize::Byte) => "b1",
            (Self::R2, MemoryOpSize::Byte) => "b2",
            (Self::R3, MemoryOpSize::Byte) => "b3",
            (Self::R4, MemoryOpSize::Byte) => "b4",
            (Self::R5, MemoryOpSize::Byte) => "b5",
            (Self::R6, MemoryOpSize::Byte) => "b6",
            (Self::R7, MemoryOpSize::Byte) => "b7",
            (Self::R8, MemoryOpSize::Byte) => "b8",
            (Self::R9, MemoryOpSize::Byte) => "b9",
            (Self::R10, MemoryOpSize::Byte) => "b10",
            (Self::R0, MemoryOpSize::HalfWord) => "h0",
            (Self::R1, MemoryOpSize::HalfWord) => "h1",
            (Self::R2, MemoryOpSize::HalfWord) => "h2",
            (Self::R3, MemoryOpSize::HalfWord) => "h3",
            (Self::R4, MemoryOpSize::HalfWord) => "h4",
            (Self::R5, MemoryOpSize::HalfWord) => "h5",
            (Self::R6, MemoryOpSize::HalfWord) => "h6",
            (Self::R7, MemoryOpSize::HalfWord) => "h7",
            (Self::R8, MemoryOpSize::HalfWord) => "h8",
            (Self::R9, MemoryOpSize::HalfWord) => "h9",
            (Self::R10, MemoryOpSize::HalfWord) => "h10",
            (Self::R0, MemoryOpSize::Word) => "w0",
            (Self::R1, MemoryOpSize::Word) => "w1",
            (Self::R2, MemoryOpSize::Word) => "w2",
            (Self::R3, MemoryOpSize::Word) => "w3",
            (Self::R4, MemoryOpSize::Word) => "w4",
            (Self::R5, MemoryOpSize::Word) => "w5",
            (Self::R6, MemoryOpSize::Word) => "w6",
            (Self::R7, MemoryOpSize::Word) => "w7",
            (Self::R8, MemoryOpSize::Word) => "w8",
            (Self::R9, MemoryOpSize::Word) => "w9",
            (Self::R10, MemoryOpSize::Word) => "w10",
            (Self::R0, MemoryOpSize::DoubleWord) => "r0",
            (Self::R1, MemoryOpSize::DoubleWord) => "r1",
            (Self::R2, MemoryOpSize::DoubleWord) => "r2",
            (Self::R3, MemoryOpSize::DoubleWord) => "r3",
            (Self::R4, MemoryOpSize::DoubleWord) => "r4",
            (Self::R5, MemoryOpSize::DoubleWord) => "r5",
            (Self::R6, MemoryOpSize::DoubleWord) => "r6",
            (Self::R7, MemoryOpSize::DoubleWord) => "r7",
            (Self::R8, MemoryOpSize::DoubleWord) => "r8",
            (Self::R9, MemoryOpSize::DoubleWord) => "r9",
            (Self::R10, MemoryOpSize::DoubleWord) => "r10",
        }
    }

    fn get_dst(instruction: u64) -> Option<Register> {
        Self::from_num(((instruction >> 8) & 0xf) as u8)
    }

    fn get_src(instruction: u64) -> Option<Register> {
        Self::from_num(((instruction >> 12) & 0xf) as u8)
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Opcode {
    Arithmetic(ArithmeticInstruction),
    Jump(JumpInstruction),
    Memory(MemoryInstruction),
}

impl Opcode {
    fn from_raw(instruction: u64) -> Result<Self> {
        let class = OpcodeClass::from_raw(instruction);
        match class {
            OpcodeClass::Arithmetic | OpcodeClass::Arithmetic64 => Ok(Self::Arithmetic(
                ArithmeticInstruction::from_raw(instruction)?,
            )),
            OpcodeClass::Jump | OpcodeClass::Jump32 => {
                Ok(Self::Jump(JumpInstruction::from_raw(instruction)?))
            }
            OpcodeClass::Load
            | OpcodeClass::LoadReg
            | OpcodeClass::Store
            | OpcodeClass::StoreReg => Ok(Self::Memory(MemoryInstruction::from_raw(instruction)?)),
        }
    }

    fn opcode(&self) -> u8 {
        match self {
            Self::Arithmetic(arithmetic) => arithmetic.opcode(),
            Self::Jump(jump) => jump.opcode(),
            Self::Memory(memory) => memory.opcode(),
        }
    }

    fn is_wide(&self) -> bool {
        if let Self::Memory(memory_instruction) = self {
            matches!(memory_instruction.size, MemoryOpSize::DoubleWord)
                && matches!(memory_instruction.class, OpcodeClass::Load)
        } else {
            false
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Instruction {
    opcode: Opcode,
    dst_reg: Register,
    src_reg: Register,
    offset: i16,
    imm: i64,
}

impl Instruction {
    /// Given a `u64` slice, this decodes a single instruction. Since eBPF instructions
    /// can be "wide", meaning a single instruction is represented by two 64-bit values,
    /// a slice is required. The user must check if the instruction was wide by calling
    /// `is_wide` when deciding how many instructions to advance the slice before the
    /// next invocation of this function.
    ///
    /// # Arguments
    ///
    /// * `instructions` - A slice of raw eBPF instructions.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Opcode, Register};
    ///
    /// let instructions = [ 0x000000fff81a7b ];
    /// let instruction = Instruction::decode(&instructions).unwrap();
    /// assert!(matches!(instruction.get_opcode(), Opcode::Memory(_)));
    /// assert!(matches!(instruction.get_dst_reg(), Register::R10));
    /// assert!(matches!(instruction.get_src_reg(), Register::R1));
    /// assert!(matches!(instruction.get_offset(), -8));
    /// assert!(matches!(instruction.get_imm(), 0));
    /// ```
    pub fn decode(instructions: &[u64]) -> Result<Self> {
        if instructions.is_empty() {
            bail!("No instructions remaining to decode");
        }

        let opcode = Opcode::from_raw(instructions[0])?;
        let dst_reg = Register::get_dst(instructions[0]).context("Invalid destination register")?;
        let src_reg = Register::get_src(instructions[0]).context("Invalid source register")?;
        let offset = ((instructions[0] >> 16) & 0xffff) as i16;
        let mut imm = ((instructions[0] >> 32) & 0xffffffff) as i64;
        if opcode.is_wide() {
            if instructions.len() < 2 {
                bail!("Wide instruction was truncated");
            } else {
                imm |= (instructions[1] as u64 & 0xffffffff00000000) as i64;
            }
        }

        Ok(Self {
            opcode,
            dst_reg,
            src_reg,
            offset,
            imm,
        })
    }

    /// Encodes this instruction object into raw 64-bit eBPF instructions. If the
    /// instruction was wide, the second entry of the tuple is populated with the
    /// extended part of the instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::load(Register::R10, 0xdeadbeef, MemoryOpSize::DoubleWord);
    /// assert!(instruction.is_wide());
    /// assert_eq!(instruction.encode(), (0xdeadbeef00000a18, Some(0)));
    /// ```
    pub fn encode(&self) -> (u64, Option<u64>) {
        let opcode = self.opcode.opcode() as u64;
        let dst_reg = self.dst_reg.as_num() as u64;
        let src_reg = self.src_reg.as_num() as u64;
        let offset = (self.offset as u64) & 0xffff;
        let imm = self.imm as u64;
        let n = opcode | (dst_reg << 8) | (src_reg << 12) | (offset << 16) | (imm << 32);
        if self.opcode.is_wide() {
            let x = imm & 0xffffffff00000000;
            (n, Some(x))
        } else {
            (n, None)
        }
    }

    /// Returns the "opcode" portion of this instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Opcode, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R5, Register::R6);
    /// assert!(matches!(instruction.get_opcode(), Opcode::Arithmetic(_)));
    ///
    /// let instruction = Instruction::exit();
    /// assert!(matches!(instruction.get_opcode(), Opcode::Jump(_)));
    ///
    /// let instruction = Instruction::load(Register::R10, 0xdeadbeef, MemoryOpSize::Byte);
    /// assert!(matches!(instruction.get_opcode(), Opcode::Memory(_)));
    ///
    /// let instruction = Instruction::store64(Register::R10, 0, 0xdeadbeef);
    /// assert!(matches!(instruction.get_opcode(), Opcode::Memory(_)));
    /// ```
    pub fn get_opcode(&self) -> Opcode {
        self.opcode
    }

    /// Returns "source register" portion of this instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R2, Register::R3);
    /// assert_eq!(instruction.get_src_reg(), Register::R3);
    /// ```
    pub fn get_src_reg(&self) -> Register {
        self.src_reg
    }

    /// Returns "destination register" portion of this instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R2, Register::R3);
    /// assert_eq!(instruction.get_dst_reg(), Register::R2);
    /// ```
    pub fn get_dst_reg(&self) -> Register {
        self.dst_reg
    }

    /// Returns the "offset" portion of this instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store64(Register::R10, -300, 0);
    /// assert_eq!(instruction.get_offset(), -300);
    /// ```
    pub fn get_offset(&self) -> i16 {
        self.offset
    }

    /// Returns the "immediate" portion of this instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store64(Register::R10, 0, 0xffbbccdd);
    /// assert_eq!(instruction.get_imm(), 0xffbbccdd);
    /// ```
    pub fn get_imm(&self) -> i64 {
        self.imm
    }

    /// Returns whether this instruction is wide or not. That is, if it's
    /// represented by two 64-bit values when encoded.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::load(Register::R9, 0xdeadbeef, MemoryOpSize::DoubleWord);
    /// assert!(instruction.is_wide());
    /// ```
    pub fn is_wide(&self) -> bool {
        self.opcode.is_wide()
    }

    /// Helper function for encoding immediate ALU instructions.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register on which the operation is performed.
    /// * `imm` - The immediate value of the operation.
    /// * `op` - The type of arithmetic operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Register};
    ///
    /// let instruction = Instruction::alu32(Register::R1, -10000, ArithmeticOperation::Add);
    /// assert_eq!(instruction.encode(), (0xffffd8f000000104, None))
    /// ```
    pub const fn alu32(reg: Register, imm: i32, op: ArithmeticOperation) -> Self {
        let opcode = Opcode::Arithmetic(ArithmeticInstruction {
            class: OpcodeClass::Arithmetic,
            source: SourceOperand::Immediate,
            operation: op,
            order: SwapOrder::Little,
        });

        Self {
            opcode,
            dst_reg: reg,
            src_reg: Register::R0,
            offset: 0,
            imm: imm as i64,
        }
    }

    /// Helper function for encoding 64-bit immediate ALU instructions.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register on which the operation is performed.
    /// * `imm` - The immediate value of the operation.
    /// * `op` - The type of arithmetic operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Register};
    ///
    /// let instruction = Instruction::alu64(Register::R1, -10000, ArithmeticOperation::Add);
    /// assert_eq!(instruction.encode(), (0xffffd8f000000107, None))
    /// ```
    pub const fn alu64(reg: Register, imm: i32, op: ArithmeticOperation) -> Self {
        let opcode = Opcode::Arithmetic(ArithmeticInstruction {
            class: OpcodeClass::Arithmetic64,
            source: SourceOperand::Immediate,
            operation: op,
            order: SwapOrder::Little,
        });

        Self {
            opcode,
            dst_reg: reg,
            src_reg: Register::R0,
            offset: 0,
            imm: imm as i64,
        }
    }

    /// Helper function for encoding register ALU instructions.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    /// * `op` - The type of arithmetic operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Register};
    ///
    /// let instruction = Instruction::alux32(Register::R1, Register::R2, ArithmeticOperation::Mul);
    /// assert_eq!(instruction.encode(), (0x212c, None))
    /// ```
    pub const fn alux32(dst_reg: Register, src_reg: Register, op: ArithmeticOperation) -> Self {
        let opcode = Opcode::Arithmetic(ArithmeticInstruction {
            class: OpcodeClass::Arithmetic,
            source: SourceOperand::Register,
            operation: op,
            order: SwapOrder::Little,
        });

        Self {
            opcode,
            dst_reg,
            src_reg,
            offset: 0,
            imm: 0,
        }
    }

    /// Helper function for encoding 64-bit register ALU instructions.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    /// * `op` - The type of arithmetic operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Register};
    ///
    /// let instruction = Instruction::alux64(Register::R1, Register::R2, ArithmeticOperation::Mul);
    /// assert_eq!(instruction.encode(), (0x212f, None))
    /// ```
    pub const fn alux64(dst_reg: Register, src_reg: Register, op: ArithmeticOperation) -> Self {
        let opcode = Opcode::Arithmetic(ArithmeticInstruction {
            class: OpcodeClass::Arithmetic64,
            source: SourceOperand::Register,
            operation: op,
            order: SwapOrder::Little,
        });

        Self {
            opcode,
            dst_reg,
            src_reg,
            offset: 0,
            imm: 0,
        }
    }

    /// Helper function for encoding 32-bit immediate add instructions. Equivalent to calling
    /// `Instruction::alu32(reg, imm, ArithmeticOperation::Add)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register on which the operation is performed.
    /// * `imm` - The immediate value of the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::add32(Register::R1, -10000);
    /// assert_eq!(instruction.encode(), (0xffffd8f000000104, None))
    /// ```
    pub const fn add32(reg: Register, imm: i32) -> Self {
        Self::alu32(reg, imm, ArithmeticOperation::Add)
    }

    /// Helper function for encoding 64-bit immediate add instructions. Equivalent to calling
    /// `Instruction::alu64(reg, imm, ArithmeticOperation::Add)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register on which the operation is performed.
    /// * `imm` - The immediate value of the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::add64(Register::R1, -10000);
    /// assert_eq!(instruction.encode(), (0xffffd8f000000107, None))
    /// ```
    pub const fn add64(reg: Register, imm: i32) -> Self {
        Self::alu64(reg, imm, ArithmeticOperation::Add)
    }

    /// Helper function for encoding 32-bit register add instructions. Equivalent to calling
    /// `Instruction::alux32(dst_reg, src_reg, ArithmeticOperation::Add)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{ArithmeticOperation, Instruction, Register};
    ///
    /// let instruction = Instruction::addx32(Register::R1, Register::R2);
    /// assert_eq!(instruction.encode(), (0x210c, None))
    /// ```
    pub const fn addx32(dst_reg: Register, src_reg: Register) -> Self {
        Self::alux32(dst_reg, src_reg, ArithmeticOperation::Add)
    }

    /// Helper function for encoding 64-bit register add instructions. Equivalent to calling
    /// `Instruction::alux64(dst_reg, src_reg, ArithmeticOperation::Add)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::addx64(Register::R1, Register::R2);
    /// assert_eq!(instruction.encode(), (0x210f, None))
    /// ```
    pub const fn addx64(dst_reg: Register, src_reg: Register) -> Self {
        Self::alux64(dst_reg, src_reg, ArithmeticOperation::Add)
    }

    /// Helper function for encoding immediate 32-bit ALU move instructions. Equivalent to
    /// calling `Instruction::alu32(reg, imm, ArithmeticOperation::Mov)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register involved in the operation.
    /// * `imm` - The immediate value to move into the register.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::mov32(Register::R7, 0xfffffff);
    /// assert_eq!(instruction.encode(), (0xfffffff000007b4, None))
    /// ```
    pub const fn mov32(reg: Register, imm: i32) -> Self {
        Self::alu32(reg, imm, ArithmeticOperation::Mov)
    }

    /// Helper function for encoding immediate 64-bit ALU move instructions. Equivalent to
    /// calling `Instruction::alu64(reg, imm, ArithmeticOperation::Mov)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register involved in the operation.
    /// * `imm` - The immediate value to move into the register.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::mov64(Register::R7, 0xfffffff);
    /// assert_eq!(instruction.encode(), (0xfffffff000007b7, None))
    /// ```
    pub const fn mov64(reg: Register, imm: i32) -> Self {
        Self::alu64(reg, imm, ArithmeticOperation::Mov)
    }

    /// Helper function for encoding register 32-bit ALU move instructions. Equivalent to
    /// calling `Instruction::alux32(dst_reg, src_reg, ArithmeticOperation::Mov)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::movx32(Register::R7, Register::R8);
    /// assert_eq!(instruction.encode(), (0x87bc, None))
    /// ```
    pub const fn movx32(dst_reg: Register, src_reg: Register) -> Self {
        Self::alux32(dst_reg, src_reg, ArithmeticOperation::Mov)
    }

    /// Helper function for encoding register 64-bit ALU move instructions. Equivalent to
    /// calling `Instruction::alux64(dst_reg, src_reg, ArithmeticOperation::Mov)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The destination register involved in the operation.
    /// * `src_reg` - The source register involved in the operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::movx64(Register::R7, Register::R8);
    /// assert_eq!(instruction.encode(), (0x87bf, None))
    /// ```
    pub const fn movx64(dst_reg: Register, src_reg: Register) -> Self {
        Self::alux64(dst_reg, src_reg, ArithmeticOperation::Mov)
    }

    /// Helper function for creating instructions that load values from memory.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register to load the value into.
    /// * `imm` - The memory address.
    /// * `size` - The size of the load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::load(Register::R9, 0x7fff880000000000, MemoryOpSize::Byte);
    /// assert_eq!(instruction.encode(), (0x910, None))
    /// ```
    pub const fn load(reg: Register, imm: i64, size: MemoryOpSize) -> Self {
        let opcode = Opcode::Memory(MemoryInstruction {
            class: OpcodeClass::Load,
            size,
            mode: MemoryOpMode::Immediate,
        });

        Self {
            opcode,
            dst_reg: reg,
            src_reg: Register::R0,
            offset: 0,
            imm,
        }
    }

    /// Helper function for creating instructions that load values from memory. This is
    /// currently only used for "special" loads, ie: when loading a map fd into a register,
    /// the eBPF verifier will replace the fd number with the map's virtual address.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register to load the value into.
    /// * `imm` - The memory address.
    /// * `load_type` - The type to assign to the load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpLoadType, Register};
    ///
    /// let instruction = Instruction::loadtype(Register::R4, 3, MemoryOpLoadType::Map);
    /// assert_eq!(instruction.encode(), (0x300001418, Some(0)));
    /// assert_eq!(instruction.get_src_reg(), Register::R1);
    /// ```
    pub const fn loadtype(reg: Register, imm: i64, load_type: MemoryOpLoadType) -> Self {
        let opcode = Opcode::Memory(MemoryInstruction {
            class: OpcodeClass::Load,
            size: MemoryOpSize::DoubleWord,
            mode: MemoryOpMode::Immediate,
        });

        Self {
            opcode,
            dst_reg: reg,
            src_reg: load_type.register_identifier(),
            offset: 0,
            imm,
        }
    }

    /// Helper function for creating instructions that load values from memory into a register
    /// using one register as the address value.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register to load the value into.
    /// * `src_reg` - The register holding the memory address.
    /// * `offset` - The offset from the address in `src_reg` to load.
    /// * `size` - The size of the value to load from the memory location.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::loadx(Register::R4, Register::R5, -16, MemoryOpSize::Byte);
    /// assert_eq!(instruction.encode(), (0xfff05471, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// ```
    pub const fn loadx(
        dst_reg: Register,
        src_reg: Register,
        offset: i16,
        size: MemoryOpSize,
    ) -> Self {
        let opcode = Opcode::Memory(MemoryInstruction {
            class: OpcodeClass::LoadReg,
            size,
            mode: MemoryOpMode::Memory,
        });

        Self {
            opcode,
            dst_reg,
            src_reg,
            offset,
            imm: 0,
        }
    }

    /// Helper function for creating instructions that load a byte from memory. Equivalent
    /// to calling `Instruction::loadx(dst_reg, src_reg, offset, MemoryOpSize::Byte)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register to load the value into.
    /// * `src_reg` - The register holding the memory address.
    /// * `offset` - The offset from the address in `src_reg` to load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::loadx8(Register::R2, Register::R3, -16);
    /// assert_eq!(instruction.encode(), (0xfff03271, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R2);
    /// assert_eq!(instruction.get_src_reg(), Register::R3);
    /// ```
    pub const fn loadx8(dst_reg: Register, src_reg: Register, offset: i16) -> Self {
        Self::loadx(dst_reg, src_reg, offset, MemoryOpSize::Byte)
    }

    /// Helper function for creating instructions that load a half word from memory. Equivalent
    /// to calling `Instruction::loadx(dst_reg, src_reg, offset, MemoryOpSize::HalfWord)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register to load the value into.
    /// * `src_reg` - The register holding the memory address.
    /// * `offset` - The offset from the address in `src_reg` to load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::loadx16(Register::R1, Register::R2, -16);
    /// assert_eq!(instruction.encode(), (0xfff02169, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R1);
    /// assert_eq!(instruction.get_src_reg(), Register::R2);
    /// ```
    pub const fn loadx16(dst_reg: Register, src_reg: Register, offset: i16) -> Self {
        Self::loadx(dst_reg, src_reg, offset, MemoryOpSize::HalfWord)
    }

    /// Helper function for creating instructions that load a word from memory. Equivalent
    /// to calling `Instruction::loadx(dst_reg, src_reg, offset, MemoryOpSize::Word)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register to load the value into.
    /// * `src_reg` - The register holding the memory address.
    /// * `offset` - The offset from the address in `src_reg` to load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::loadx32(Register::R8, Register::R9, -16);
    /// assert_eq!(instruction.encode(), (0xfff09861, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R8);
    /// assert_eq!(instruction.get_src_reg(), Register::R9);
    /// ```
    pub const fn loadx32(dst_reg: Register, src_reg: Register, offset: i16) -> Self {
        Self::loadx(dst_reg, src_reg, offset, MemoryOpSize::Word)
    }

    /// Helper function for creating instructions that load a double word from memory. Equivalent
    /// to calling `Instruction::loadx(dst_reg, src_reg, offset, MemoryOpSize::DoubleWord)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register to load the value into.
    /// * `src_reg` - The register holding the memory address.
    /// * `offset` - The offset from the address in `src_reg` to load.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::loadx64(Register::R7, Register::R10, -16);
    /// assert_eq!(instruction.encode(), (0xfff0a779, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R7);
    /// assert_eq!(instruction.get_src_reg(), Register::R10);
    /// ```
    pub const fn loadx64(dst_reg: Register, src_reg: Register, offset: i16) -> Self {
        Self::loadx(dst_reg, src_reg, offset, MemoryOpSize::DoubleWord)
    }

    /// Helper function for creating instructions that store immediate values to memory.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register containing the memory address.
    /// * `offset` - The offset from the address held in `reg` to store the value.
    /// * `imm` - The immediate value to store.
    /// * `size` - The size of the store operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::store(Register::R1, 2808, i64::max_value(),
    /// MemoryOpSize::DoubleWord);
    /// assert_eq!(instruction.encode(), (0xffffffff0af8017a, None));
    /// assert_eq!(instruction.get_dst_reg(), Register::R1);
    /// ```
    pub const fn store(reg: Register, offset: i16, imm: i64, size: MemoryOpSize) -> Self {
        let opcode = Opcode::Memory(MemoryInstruction {
            class: OpcodeClass::Store,
            size,
            mode: MemoryOpMode::Memory,
        });

        Self {
            opcode,
            dst_reg: reg,
            src_reg: Register::R0,
            offset,
            imm,
        }
    }

    /// Helper function for creating instructions that store a byte to a memory address.
    /// Equivalent to calling `Instruction::store(reg, offset, imm, MemoryOpSize::Byte)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register containing the memory address.
    /// * `offset` - The offset from the address held in `reg` to store the value.
    /// * `imm` - The immediate value to store.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store8(Register::R2, i16::min_value(), i8::max_value());
    /// assert_eq!(instruction.get_dst_reg(), Register::R2);
    /// assert_eq!(instruction.get_offset(), i16::min_value());
    /// assert_eq!(instruction.get_imm(), i8::max_value() as i64);
    /// ```
    pub const fn store8(reg: Register, offset: i16, imm: i8) -> Self {
        Self::store(reg, offset, imm as i64, MemoryOpSize::Byte)
    }

    /// Helper function for creating instructions that store a half word to a memory address.
    /// Equivalent to calling `Instruction::store(reg, offset, imm, MemoryOpSize::HalfWord)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register containing the memory address.
    /// * `offset` - The offset from the address held in `reg` to store the value.
    /// * `imm` - The immediate value to store.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store16(Register::R3, i16::max_value(), i16::min_value());
    /// assert_eq!(instruction.get_dst_reg(), Register::R3);
    /// assert_eq!(instruction.get_offset(), i16::max_value());
    /// assert_eq!(instruction.get_imm(), i16::min_value() as i64);
    /// ```
    pub const fn store16(reg: Register, offset: i16, imm: i16) -> Self {
        Self::store(reg, offset, imm as i64, MemoryOpSize::HalfWord)
    }

    /// Helper function for creating instructions that store a word to a memory address.
    /// Equivalent to calling `Instruction::store(reg, offset, imm, MemoryOpSize::Word)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register containing the memory address.
    /// * `offset` - The offset from the address held in `reg` to store the value.
    /// * `imm` - The immediate value to store.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store32(Register::R4, i16::max_value(), i32::min_value());
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_offset(), i16::max_value());
    /// assert_eq!(instruction.get_imm(), i32::min_value() as i64);
    /// ```
    pub const fn store32(reg: Register, offset: i16, imm: i32) -> Self {
        Self::store(reg, offset, imm as i64, MemoryOpSize::Word)
    }

    /// Helper function for creating instructions that store a double word to a memory address.
    /// Equivalent to calling `Instruction::store(reg, offset, imm, MemoryOpSize::DoubleWord)`.
    ///
    /// # Arguments
    ///
    /// * `reg` - The register containing the memory address.
    /// * `offset` - The offset from the address held in `reg` to store the value.
    /// * `imm` - The immediate value to store.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::store64(Register::R4, i16::max_value(), i64::min_value());
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_offset(), i16::max_value());
    /// assert_eq!(instruction.get_imm(), i64::min_value() as i64);
    /// ```
    pub const fn store64(reg: Register, offset: i16, imm: i64) -> Self {
        Self::store(reg, offset, imm, MemoryOpSize::DoubleWord)
    }

    /// Helper function or creating instructions that store register values to memory.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register holding the address of the store operation.
    /// * `offset` - The offset, from `dst_reg`, to store the value.
    /// * `src_reg` - The register holding the value to be stored.
    /// * `size` - The size of the store operation.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, MemoryOpSize, Register};
    ///
    /// let instruction = Instruction::storex(Register::R4, -128, Register::R5, MemoryOpSize::Word);
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// assert_eq!(instruction.get_offset(),-128);
    /// assert_eq!(instruction.encode(), (0xff805463, None));
    /// ```
    pub const fn storex(
        dst_reg: Register,
        offset: i16,
        src_reg: Register,
        size: MemoryOpSize,
    ) -> Self {
        let opcode = Opcode::Memory(MemoryInstruction {
            class: OpcodeClass::StoreReg,
            size,
            mode: MemoryOpMode::Memory,
        });

        Self {
            opcode,
            dst_reg,
            src_reg,
            offset,
            imm: 0,
        }
    }

    /// Helper function or creating instructions that store a byte from a register into memory.
    /// Equivalent to `Instruction::storex(dst_reg, offset, src_reg, MemoryOpSize::Byte)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register holding the address of the store operation.
    /// * `offset` - The offset, from `dst_reg`, to store the value.
    /// * `src_reg` - The register holding the value to be stored.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::storex8(Register::R4, -128, Register::R5);
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// assert_eq!(instruction.get_offset(),-128);
    /// assert_eq!(instruction.encode(), (0xff805473, None));
    /// ```
    pub const fn storex8(dst_reg: Register, offset: i16, src_reg: Register) -> Self {
        Self::storex(dst_reg, offset, src_reg, MemoryOpSize::Byte)
    }

    /// Helper function or creating instructions that store a half word from a register into memory.
    /// Equivalent to `Instruction::storex(dst_reg, offset, src_reg, MemoryOpSize::HalfWord)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register holding the address of the store operation.
    /// * `offset` - The offset, from `dst_reg`, to store the value.
    /// * `src_reg` - The register holding the value to be stored.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::storex16(Register::R4, -128, Register::R5);
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// assert_eq!(instruction.get_offset(),-128);
    /// assert_eq!(instruction.encode(), (0xff80546b, None));
    /// ```
    pub const fn storex16(dst_reg: Register, offset: i16, src_reg: Register) -> Self {
        Self::storex(dst_reg, offset, src_reg, MemoryOpSize::HalfWord)
    }

    /// Helper function or creating instructions that store a word from a register into memory.
    /// Equivalent to `Instruction::storex(dst_reg, offset, src_reg, MemoryOpSize::Word)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register holding the address of the store operation.
    /// * `offset` - The offset, from `dst_reg`, to store the value.
    /// * `src_reg` - The register holding the value to be stored.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::storex32(Register::R4, -128, Register::R5);
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// assert_eq!(instruction.get_offset(),-128);
    /// assert_eq!(instruction.encode(), (0xff805463, None));
    /// ```
    pub const fn storex32(dst_reg: Register, offset: i16, src_reg: Register) -> Self {
        Self::storex(dst_reg, offset, src_reg, MemoryOpSize::Word)
    }

    /// Helper function or creating instructions that store a double word from a register into memory.
    /// Equivalent to `Instruction::storex(dst_reg, offset, src_reg, MemoryOpSize::DoubleWord)`.
    ///
    /// # Arguments
    ///
    /// * `dst_reg` - The register holding the address of the store operation.
    /// * `offset` - The offset, from `dst_reg`, to store the value.
    /// * `src_reg` - The register holding the value to be stored.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction, Register};
    ///
    /// let instruction = Instruction::storex64(Register::R4, -128, Register::R5);
    /// assert_eq!(instruction.get_dst_reg(), Register::R4);
    /// assert_eq!(instruction.get_src_reg(), Register::R5);
    /// assert_eq!(instruction.get_offset(),-128);
    /// assert_eq!(instruction.encode(), (0xff80547b, None));
    /// ```
    pub const fn storex64(dst_reg: Register, offset: i16, src_reg: Register) -> Self {
        Self::storex(dst_reg, offset, src_reg, MemoryOpSize::DoubleWord)
    }

    /// Helper function for creating instructions that call eBPF helpers.
    ///
    /// # Arguments
    ///
    /// * `n` - The number of the helper function to call.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction};
    /// const PROBE_WRITE_USER_NUM: u32 = 36;
    ///
    /// let instruction = Instruction::call(PROBE_WRITE_USER_NUM);
    /// assert_eq!(instruction.encode(), (0x2400000085, None));
    /// ```
    pub const fn call(n: u32) -> Self {
        let opcode = Opcode::Jump(JumpInstruction {
            class: OpcodeClass::Jump,
            source: SourceOperand::Immediate,
            operation: JumpOperation::Call,
        });

        Self {
            opcode,
            dst_reg: Register::R0,
            src_reg: Register::R0,
            offset: 0,
            imm: n as i64,
        }
    }

    /// Helper function for creating an exit instruction.
    ///
    /// # Example
    /// ```
    /// use bpf_ins::{Instruction};
    ///
    /// let instruction = Instruction::exit();
    /// assert_eq!(instruction.encode(), (0x95, None));
    /// ```
    pub const fn exit() -> Self {
        let opcode = Opcode::Jump(JumpInstruction {
            class: OpcodeClass::Jump,
            source: SourceOperand::Immediate,
            operation: JumpOperation::Exit,
        });

        Self {
            opcode,
            dst_reg: Register::R0,
            src_reg: Register::R0,
            offset: 0,
            imm: 0,
        }
    }
}