rocketmq-protocol 1.1.0

Runtime-neutral RocketMQ wire protocol contracts
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
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Cow;
use std::collections::HashMap;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::str;

use byteorder::BigEndian;
use byteorder::ByteOrder;
use bytes::Buf;
use bytes::BufMut;
use bytes::Bytes;
use bytes::BytesMut;
use cheetah_string::CheetahBuilder;
use cheetah_string::CheetahString;
use memchr::memchr;

use crate::common::compression::compressor_factory::CompressorFactory;
use rocketmq_model::codec::string_to_bytes;
use rocketmq_model::common::message::message_client_ext::MessageClientExt;
use rocketmq_model::common::message::message_ext::MessageExt;
use rocketmq_model::common::message::message_id::MessageId;
use rocketmq_model::common::message::message_property::MessageProperties;
use rocketmq_model::common::message::message_single::Message;
use rocketmq_model::common::message::MessageConst;
use rocketmq_model::common::message::MessageTrait;
use rocketmq_model::common::message::MessageVersion;
use rocketmq_model::common::sys_flag::message_sys_flag::MessageSysFlag;
use rocketmq_model::utils::crc32_utils::crc32;
use rocketmq_model::utils::message_utils::build_message_id_cheetah;

pub const CHARSET_UTF8: &str = "UTF-8";
pub const MESSAGE_MAGIC_CODE_POSITION: usize = 4;
pub const MESSAGE_FLAG_POSITION: usize = 16;
pub const MESSAGE_PHYSIC_OFFSET_POSITION: usize = 28;
pub const MESSAGE_STORE_TIMESTAMP_POSITION: usize = 56;
pub const MESSAGE_MAGIC_CODE: i32 = -626843481;
pub const MESSAGE_MAGIC_CODE_V2: i32 = -626843477;
pub const BLANK_MAGIC_CODE: i32 = -875286124;
pub const NAME_VALUE_SEPARATOR: char = '\u{0001}';
pub const PROPERTY_SEPARATOR: char = '\u{0002}';
pub const PHY_POS_POSITION: usize = 4 + 4 + 4 + 4 + 4 + 8;
pub const QUEUE_OFFSET_POSITION: usize = 4 + 4 + 4 + 4 + 4;
pub const SYSFLAG_POSITION: usize = 4 + 4 + 4 + 4 + 4 + 8 + 8;
pub const BORN_TIMESTAMP_POSITION: usize = 4 + 4 + 4 + 4 + 4 + 8 + 8 + 4 + 8;

macro_rules! decode_message_properties_into {
    ($map:ident, $properties:expr) => {{
        let properties = $properties;
        let bytes = properties.as_bytes();
        let mut index = 0;
        let len = bytes.len();
        while index < len {
            let new_index = memchr(PROPERTY_SEPARATOR as u8, &bytes[index..]).map_or(len, |i| index + i);
            if new_index - index >= 3 {
                if let Some(kv_sep_index) = memchr(NAME_VALUE_SEPARATOR as u8, &bytes[index..new_index]) {
                    let kv_sep_index = index + kv_sep_index;
                    if kv_sep_index > index && kv_sep_index < new_index - 1 {
                        let k = &properties[index..kv_sep_index];
                        let v = &properties[kv_sep_index + 1..new_index];
                        $map.insert(CheetahString::from_slice(k), CheetahString::from_slice(v));
                    }
                }
            }
            index = new_index + 1;
        }
    }};
}

fn get_i16_checked(buffer: &mut Bytes) -> Option<i16> {
    if buffer.remaining() < 2 {
        None
    } else {
        Some(buffer.get_i16())
    }
}

fn get_i32_checked(buffer: &mut Bytes) -> Option<i32> {
    if buffer.remaining() < 4 {
        None
    } else {
        Some(buffer.get_i32())
    }
}

fn split_to_checked(buffer: &mut Bytes, len: usize) -> Option<Bytes> {
    if buffer.remaining() < len {
        None
    } else {
        Some(buffer.split_to(len))
    }
}

pub fn string_to_message_properties(properties: Option<&CheetahString>) -> HashMap<CheetahString, CheetahString> {
    string_to_message_properties_with_additional(properties, 0)
}

/// Decodes message properties into a map with room for `additional` more entries.
///
/// See [`str_to_message_properties_with_additional`].
pub fn string_to_message_properties_with_additional(
    properties: Option<&CheetahString>,
    additional: usize,
) -> HashMap<CheetahString, CheetahString> {
    str_to_message_properties_with_additional(properties.map(CheetahString::as_str), additional)
}

pub fn str_to_message_properties(properties: Option<&str>) -> HashMap<CheetahString, CheetahString> {
    str_to_message_properties_with_additional(properties, 0)
}

/// Decodes message properties into a map with room for `additional` more entries.
///
/// The map is sized for every encoded pair before decoding, so it is not grown and rehashed while
/// the pairs are inserted. A caller that inserts a known number of properties afterwards passes
/// that number as `additional`.
pub fn str_to_message_properties_with_additional(
    properties: Option<&str>,
    additional: usize,
) -> HashMap<CheetahString, CheetahString> {
    let Some(properties) = properties else {
        return HashMap::with_capacity(additional);
    };
    // One name/value separator per encoded pair; malformed pairs only leave spare capacity.
    let pairs = properties
        .bytes()
        .filter(|&byte| byte == NAME_VALUE_SEPARATOR as u8)
        .count();
    let mut map = HashMap::with_capacity(pairs + additional);
    decode_message_properties_into!(map, properties);
    map
}

/// Encodes message properties with RocketMQ's name/value and property
/// separators.
#[inline]
pub fn message_properties_to_string(properties: &HashMap<CheetahString, CheetahString>) -> CheetahString {
    if properties.is_empty() {
        return CheetahString::empty();
    }

    // The exact length: the builder's string is frozen into shared storage, which shrinks a
    // string with spare capacity by reallocating it first.
    let capacity = properties
        .iter()
        .map(|(name, value)| name.len() + value.len() + 2)
        .sum();

    let mut builder = CheetahBuilder::with_capacity(capacity);
    for (name, value) in properties.iter() {
        builder.push_str(name.as_str());
        builder.push(NAME_VALUE_SEPARATOR);

        builder.push_str(value.as_str());
        builder.push(PROPERTY_SEPARATOR);
    }
    builder.finish()
}

/// Converts UTF-8 message protocol bytes into a [`CheetahString`], preserving
/// `String::from_utf8_lossy` compatibility for invalid input.
pub fn cheetah_from_utf8_lossy(bytes: &[u8]) -> CheetahString {
    match String::from_utf8_lossy(bytes) {
        Cow::Borrowed(value) => CheetahString::from_slice(value),
        Cow::Owned(value) => CheetahString::from_string(value),
    }
}

pub fn decode_client(
    byte_buffer: &mut Bytes,
    read_body: bool,
    de_compress_body: bool,
    is_set_properties_string: bool,
    check_crc: bool,
) -> Option<MessageClientExt> {
    decode(
        byte_buffer,
        read_body,
        de_compress_body,
        true,
        is_set_properties_string,
        check_crc,
    )
    .map(|msg_ext| MessageClientExt {
        message_ext_inner: msg_ext,
    })
}

/// Decodes one stored message frame from the front of `byte_buffer` and advances past it.
///
/// - `read_body` keeps the body, as a slice of `byte_buffer` unless it is decompressed.
/// - `de_compress_body` decompresses a body whose system flag marks it compressed.
/// - `is_client` lets the properties share the frame with a retained wire body instead of copying
///   them. Use it only where the message owns the reply frame, as client Pull and POP decoding do.
///   The frame then stays alive as long as the message or any clone of its properties; call
///   `MessageProperties::detach_from_frame` on a clone that is cached independently. Taking or
///   replacing the body detaches the properties automatically.
/// - `is_set_properties_string` also stores the raw property text under `propertiesString`.
/// - `check_crc` rejects a read body whose CRC32 differs from the stored one.
///
/// Returns `None` if the frame is malformed, the CRC check fails or decompression fails.
pub fn decode(
    byte_buffer: &mut Bytes,
    read_body: bool,
    de_compress_body: bool,
    is_client: bool,
    is_set_properties_string: bool,
    check_crc: bool,
) -> Option<MessageExt> {
    decode_with_previous_topic(
        byte_buffer,
        read_body,
        de_compress_body,
        is_client,
        is_set_properties_string,
        check_crc,
        None,
    )
}

fn decode_with_previous_topic(
    byte_buffer: &mut Bytes,
    read_body: bool,
    de_compress_body: bool,
    is_client: bool,
    is_set_properties_string: bool,
    check_crc: bool,
    previous_topic: Option<&CheetahString>,
) -> Option<MessageExt> {
    use crate::protocol::body::message_codec::PropertiesString;

    let properties_string = if is_set_properties_string {
        PropertiesString::Keep
    } else {
        PropertiesString::Skip
    };
    let (frame, encoded_properties) =
        crate::protocol::body::message_codec::decode_message_frame_with_encoded_properties(
            byte_buffer,
            properties_string,
            previous_topic,
        )
        .ok()?;

    if read_body && !frame.body.is_empty() && check_crc && crc32(&frame.body) != frame.body_crc {
        return None;
    }

    let mut msg_ext = MessageExt::default();
    msg_ext.set_store_size(frame.store_size);
    msg_ext.set_body_crc(frame.body_crc);
    msg_ext.set_queue_id(frame.queue_id);
    msg_ext.message.set_flag(frame.flag);
    msg_ext.set_queue_offset(frame.queue_offset);
    msg_ext.set_commit_log_offset(frame.commit_log_offset);
    msg_ext.set_sys_flag(frame.sys_flag);
    msg_ext.set_born_timestamp(frame.born_timestamp);
    msg_ext.set_born_host(frame.born_host);
    msg_ext.set_store_timestamp(frame.store_timestamp);
    msg_ext.set_store_host(frame.store_host);
    msg_ext.set_reconsume_times(frame.reconsume_times);
    msg_ext.set_prepared_transaction_offset(frame.prepared_transaction_offset);
    msg_ext.message.set_topic(frame.topic);

    let decompress = de_compress_body && frame.sys_flag & MessageSysFlag::COMPRESSED_FLAG != 0;
    let retain_frame = is_client && read_body && !frame.body.is_empty() && !decompress;
    if read_body && !frame.body.is_empty() {
        let mut body = frame.body;
        if decompress {
            let compression_type = MessageSysFlag::try_get_compression_type(frame.sys_flag).ok()?;
            body = compression_type.try_decompression(&body).ok()?;
        }
        msg_ext.message.set_body(Some(body));
    }

    // Parsed on first whole-map access: a consumer that reads its tags and sets a few properties
    // never builds the map.
    let mut properties = if retain_frame {
        MessageProperties::from_frame_bytes(encoded_properties)
    } else {
        MessageProperties::from_encoded(encoded_properties)
    };
    if is_set_properties_string && !frame.properties_string.is_empty() {
        properties.put(
            CheetahString::from_static_str("propertiesString"),
            frame.properties_string,
        );
    }
    *msg_ext.message.properties_mut() = properties;
    msg_ext.set_msg_id(build_message_id_cheetah(frame.store_host, frame.commit_log_offset));

    Some(msg_ext)
}

pub fn count_inner_msg_num(bytes: Option<Bytes>) -> u32 {
    match bytes {
        None => 0,
        Some(mut bytes) => {
            let mut count = 0;
            while bytes.has_remaining() {
                let size = bytes.slice(0..4).get_i32();
                if size as usize > bytes.len() {
                    break;
                }
                let _ = bytes.split_to(size as usize);
                count += 1;
            }
            count
        }
    }
}

pub fn encode_messages(messages: &[Message]) -> Bytes {
    let mut bytes = BytesMut::new();
    for message in messages {
        encode_message_into(message, &mut bytes);
    }
    bytes.freeze()
}

pub fn encode_message(message: &Message) -> Bytes {
    let mut bytes = BytesMut::new();
    encode_message_into(message, &mut bytes);
    bytes.freeze()
}

/// Encodes one producer message directly into an existing aggregate buffer.
///
/// This uses the same Java-compatible batch wire layout as [`encode_message`] while avoiding a
/// temporary allocation for every message in a batch.
pub fn encode_message_into(message: &Message, bytes: &mut BytesMut) {
    let empty_body = Bytes::new();
    let body = message.get_body().unwrap_or(&empty_body);
    let body_len = body.len();
    let properties = message_properties_to_string(message.properties().as_map());
    let properties_bytes = properties.as_bytes();
    let properties_length = properties_bytes.len();

    let store_size = 4 // 1 TOTALSIZE
             + 4 // 2 MAGICCOD
             + 4 // 3 BODYCRC
             + 4 // 4 FLAG
             + 4 + body_len // 4 BODY
             + 2 + properties_length;

    bytes.reserve(store_size);

    // 1 TOTALSIZE
    bytes.put_i32(store_size as i32);

    // 2 MAGICCODE
    bytes.put_i32(0);

    // 3 BODYCRC
    bytes.put_u32(0);

    // 4 FLAG
    bytes.put_i32(message.flag());

    // 5 BODY
    bytes.put_i32(body_len as i32);
    bytes.put_slice(body);

    // 6 PROPERTIES
    bytes.put_i16(properties_length as i16);
    bytes.put_slice(properties_bytes);
}

pub fn decodes_batch(byte_buffer: &mut Bytes, read_body: bool, decompress_body: bool) -> Vec<MessageExt> {
    decode_batch(byte_buffer, read_body, decompress_body, false, std::convert::identity)
}

/// Decodes client Pull or POP messages. Only a body kept as a slice of the reply
/// permits its properties to share the frame. Broker reads stay detached; see
/// [`decodes_batch_with_metadata_filter`] for tag-filtered Pull replies.
pub fn decode_client_batch(byte_buffer: &mut Bytes, read_body: bool, decompress_body: bool) -> Vec<MessageExt> {
    decode_batch(byte_buffer, read_body, decompress_body, true, std::convert::identity)
}

fn decode_batch<M: MessageTrait>(
    byte_buffer: &mut Bytes,
    read_body: bool,
    decompress_body: bool,
    is_client: bool,
    wrap: impl Fn(MessageExt) -> M,
) -> Vec<M> {
    let mut messages = Vec::new();
    while byte_buffer.has_remaining() {
        let previous_topic = if is_client {
            messages.last().map(MessageTrait::topic)
        } else {
            None
        };
        if let Some(msg_ext) = decode_with_previous_topic(
            byte_buffer,
            read_body,
            decompress_body,
            is_client,
            false,
            false,
            previous_topic,
        ) {
            messages.push(wrap(msg_ext));
        } else {
            break;
        }
    }
    messages
}

fn split_next_message_frame(byte_buffer: &mut Bytes) -> Option<Bytes> {
    let remaining = byte_buffer.remaining();
    if remaining < 4 {
        return None;
    }

    let mut header = byte_buffer.clone();
    let store_size = header.get_i32();
    if store_size <= 0 || store_size as usize > remaining {
        return None;
    }

    Some(byte_buffer.split_to(store_size as usize))
}

/// Moves the body out of a client-decoded message for the metadata filter without detaching its
/// properties from the frame.
///
/// `Message::take_body` copies frame-backed properties because a message without its wire body
/// must not keep the frame alive. Here the body is either put back unchanged through
/// [`restore_body_keeping_properties`] or the whole message is dropped, so the frame never
/// outlives both.
fn take_body_keeping_properties(msg_ext: &mut MessageExt) -> Option<Bytes> {
    let properties = std::mem::take(msg_ext.message.properties_mut());
    let body = msg_ext.message.take_body();
    *msg_ext.message.properties_mut() = properties;
    body
}

/// Returns the wire body taken by [`take_body_keeping_properties`], keeping frame-backed properties.
fn restore_body_keeping_properties(msg_ext: &mut MessageExt, body: Bytes) {
    let properties = std::mem::take(msg_ext.message.properties_mut());
    msg_ext.message.set_body(Some(body));
    *msg_ext.message.properties_mut() = properties;
}

/// Decodes client Pull messages and keeps those accepted by `should_decode_body`.
///
/// The filter sees each message's metadata and properties without its body. Accepted messages get
/// their body back and, when `decompress_body` is set, decompressed. As with
/// [`decode_client_batch`], an accepted message whose body stays a slice of the reply shares the
/// reply frame with its properties, and adjacent messages with the same topic share one topic
/// value. A filter that keeps a clone of the properties it inspects must call
/// `MessageProperties::detach_from_frame` on that clone.
pub fn decodes_batch_with_metadata_filter<F>(
    byte_buffer: &mut Bytes,
    read_body: bool,
    decompress_body: bool,
    mut should_decode_body: F,
) -> Vec<MessageExt>
where
    F: FnMut(&MessageExt) -> bool,
{
    let mut messages = Vec::new();
    while byte_buffer.has_remaining() {
        let Some(frame) = split_next_message_frame(byte_buffer) else {
            break;
        };
        // Decode each frame once. The filter still sees the message without its body; only an
        // accepted message gets its body back and, when asked, decompressed.
        let mut frame = frame;
        let previous_topic = messages.last().map(MessageTrait::topic);
        let Some(mut msg_ext) =
            decode_with_previous_topic(&mut frame, read_body, false, true, false, false, previous_topic)
        else {
            break;
        };
        let body = take_body_keeping_properties(&mut msg_ext);
        if !should_decode_body(&msg_ext) {
            continue;
        }
        if let Some(body) = body {
            restore_body_keeping_properties(&mut msg_ext, body);
            if decompress_body && !decompress_message_body(&mut msg_ext) {
                break;
            }
        }
        messages.push(msg_ext);
    }
    messages
}

/// Decompresses a decoded message's body in place when its system flag marks it compressed,
/// exactly as [`decode`] does when asked to. Returns `false` when the body cannot be decompressed.
fn decompress_message_body(msg_ext: &mut MessageExt) -> bool {
    let sys_flag = msg_ext.sys_flag();
    if (sys_flag & MessageSysFlag::COMPRESSED_FLAG) != MessageSysFlag::COMPRESSED_FLAG {
        return true;
    }
    let Some(body) = msg_ext.message.get_body().filter(|body| !body.is_empty()) else {
        return true;
    };
    let Ok(compression_type) = MessageSysFlag::try_get_compression_type(sys_flag) else {
        return false;
    };
    match compression_type.try_decompression(body) {
        Ok(decompressed) => {
            msg_ext.message.set_body(Some(decompressed));
            true
        }
        Err(_) => false,
    }
}

pub fn decodes_batch_client(byte_buffer: &mut Bytes, read_body: bool, decompress_body: bool) -> Vec<MessageClientExt> {
    decode_batch(byte_buffer, read_body, decompress_body, true, MessageClientExt::new)
}

pub fn decode_messages_from(mut message_ext: MessageExt, vec_: &mut Vec<MessageExt>) {
    let Some(body) = message_ext.message.body_mut().raw_mut().as_mut() else {
        return;
    };
    let messages = decode_messages(body);
    for message in messages {
        let mut message_ext_inner = MessageExt {
            message,
            ..MessageExt::default()
        };
        message_ext_inner.set_topic(message_ext.topic().to_owned());
        message_ext_inner.queue_offset = message_ext.queue_offset;
        message_ext_inner.queue_id = message_ext.queue_id;
        message_ext_inner.set_flag(message_ext.get_flag());
        //MessageAccessor::set_properties(&mut
        // message_client_ext,message.get_properties().clone()); messageClientExt.
        // setBody(message.getBody())
        message_ext_inner.store_host = message_ext.store_host;
        message_ext_inner.born_host = message_ext.born_host;
        message_ext_inner.store_timestamp = message_ext.store_timestamp;
        message_ext_inner.born_timestamp = message_ext.born_timestamp;
        message_ext_inner.sys_flag = message_ext.sys_flag;
        message_ext_inner.commit_log_offset = message_ext.commit_log_offset;
        message_ext_inner.set_wait_store_msg_ok(message_ext.is_wait_store_msg_ok());
        vec_.push(message_ext_inner);
    }
}

pub fn decode_messages(buffer: &mut Bytes) -> Vec<Message> {
    let mut messages = Vec::new();
    while buffer.has_remaining() {
        let Some(message) = try_decode_message(buffer) else {
            break;
        };
        messages.push(message);
    }
    messages
}

pub fn decode_message(buffer: &mut Bytes) -> Message {
    try_decode_message(buffer).unwrap_or_default()
}

fn try_decode_message(buffer: &mut Bytes) -> Option<Message> {
    // 1 TOTALSIZE
    let store_size = get_i32_checked(buffer)?;
    if store_size <= 0 {
        return None;
    }

    // 2 MAGICCODE
    let _ = get_i32_checked(buffer)?;

    // 3 BODYCRC
    let _ = get_i32_checked(buffer)?;

    // 4 FLAG
    let flag = get_i32_checked(buffer)?;

    // 5 BODY
    let body_len = get_i32_checked(buffer)?;
    if body_len < 0 {
        return None;
    }
    let body = split_to_checked(buffer, body_len as usize)?;

    // 6 properties
    let properties_length = get_i16_checked(buffer)?;
    if properties_length < 0 {
        return None;
    }
    let properties = split_to_checked(buffer, properties_length as usize)?;
    //string_to_message_properties(Some(&String::from_utf8_lossy(properties.as_ref()).
    // to_string()));
    let message_properties = str_to_message_properties(Some(str::from_utf8(&properties).ok()?));

    let mut message = Message::default();
    message.set_body(Some(body));
    message.set_properties(message_properties);
    message.set_flag(flag);
    Some(message)
}

const MSG_ID_IPV4_LEN: usize = 32;
const MSG_ID_IPV6_LEN: usize = 56;

pub fn validate_message_id(msg_id: &str) -> Result<(), String> {
    let msg_id = msg_id.trim();

    if msg_id.is_empty() {
        return Err("Message ID cannot be empty".to_string());
    }

    let len = msg_id.len();
    if len != MSG_ID_IPV4_LEN && len != MSG_ID_IPV6_LEN {
        return Err(format!(
            "Invalid message ID length: {len}. Expected {MSG_ID_IPV4_LEN} characters (IPv4) or {MSG_ID_IPV6_LEN} \
             characters (IPv6)"
        ));
    }

    if !msg_id.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err("Message ID must be a valid hexadecimal string".to_string());
    }

    Ok(())
}

pub fn decode_message_id(msg_id: &str) -> Result<MessageId, String> {
    let msg_id = msg_id.trim();
    validate_message_id(msg_id)?;
    let bytes = string_to_bytes(msg_id).ok_or_else(|| "Failed to decode message ID: invalid hex string".to_string())?;
    let mut buffer = Bytes::from(bytes);
    let address = if msg_id.len() == MSG_ID_IPV4_LEN {
        let mut ip = [0u8; 4];
        buffer.copy_to_slice(&mut ip);
        let port = buffer.get_i32();
        SocketAddr::new(IpAddr::V4(Ipv4Addr::from(ip)), port as u16)
    } else {
        let mut ip = [0u8; 16];
        buffer.copy_to_slice(&mut ip);
        let port = buffer.get_i32();
        SocketAddr::new(IpAddr::V6(Ipv6Addr::from(ip)), port as u16)
    };
    Ok(MessageId {
        address,
        offset: buffer.get_i64(),
    })
}

pub fn encode(message_ext: &MessageExt, need_compress: bool) -> rocketmq_error::Result<Bytes> {
    let body = message_ext
        .get_body()
        .ok_or_else(|| crate::error::invalid_argument("message body is required"))?;
    let topic = message_ext.topic().as_bytes();
    let topic_len = topic.len();
    let properties = message_properties_to_string(message_ext.get_properties());
    let properties_bytes = properties.as_bytes();
    let properties_length = properties_bytes.len();
    let sys_flag = message_ext.sys_flag;
    let born_host_length = if (sys_flag & MessageSysFlag::BORNHOST_V6_FLAG) == 0 {
        8
    } else {
        20
    };
    let store_host_address_length = if (sys_flag & MessageSysFlag::STOREHOSTADDRESS_V6_FLAG) == 0 {
        8
    } else {
        20
    };
    let new_body = if need_compress && (sys_flag & MessageSysFlag::COMPRESSED_FLAG) == MessageSysFlag::COMPRESSED_FLAG {
        let compressor = CompressorFactory::get_compressor(MessageSysFlag::try_get_compression_type(sys_flag)?);
        let compressed_body = compressor.compress(body, 5)?;
        Some(compressed_body)
    } else {
        None
    };
    let body_len = new_body.as_ref().map_or(body.len(), |b| b.len());
    let store_size = if message_ext.store_size > 0 {
        message_ext.store_size as usize
    } else {
        4 // 1 TOTALSIZE
             + 4 // 2 MAGICCODE
             + 4 // 3 BODYCRC
             + 4 // 4 QUEUEID
             + 4 // 5 FLAG
             + 8 // 6 QUEUEOFFSET
             + 8 // 7 PHYSICALOFFSET
             + 4 // 8 SYSFLAG
             + 8 // 9 BORNTIMESTAMP
             + born_host_length // 10 BORNHOST
             + 8 // 11 STORETIMESTAMP
             + store_host_address_length // 12 STOREHOSTADDRESS
             + 4 // 13 RECONSUMETIMES
             + 8 // 14 Prepared Transaction Offset
             + 4 + body_len // 14 BODY
             + 1 + topic_len // 15 TOPIC
             + 2 + properties_length // 16 propertiesLength
    };
    let mut byte_buffer = BytesMut::with_capacity(store_size);

    // 1 TOTALSIZE
    byte_buffer.put_i32(store_size as i32);

    // 2 MAGICCODE
    byte_buffer.put_i32(MESSAGE_MAGIC_CODE);

    // 3 BODYCRC
    byte_buffer.put_u32(message_ext.body_crc);

    // 4 QUEUEID
    byte_buffer.put_i32(message_ext.queue_id);

    // 5 FLAG
    byte_buffer.put_i32(message_ext.message.flag());

    // 6 QUEUEOFFSET
    byte_buffer.put_i64(message_ext.queue_offset);

    // 7 PHYSICALOFFSET
    byte_buffer.put_i64(message_ext.commit_log_offset);

    // 8 SYSFLAG
    byte_buffer.put_i32(message_ext.sys_flag);

    // 9 BORNTIMESTAMP
    byte_buffer.put_i64(message_ext.born_timestamp);

    // 10 BORNHOST

    let born_host = message_ext.born_host;
    match born_host {
        SocketAddr::V4(value) => byte_buffer.extend(value.ip().octets()),
        SocketAddr::V6(value) => byte_buffer.extend(value.ip().octets()),
    };

    byte_buffer.put_i32(born_host.port() as i32);

    // 11 STORETIMESTAMP
    byte_buffer.put_i64(message_ext.store_timestamp);

    // 12 STOREHOST

    let store_host = message_ext.store_host;
    match store_host {
        SocketAddr::V4(value) => byte_buffer.extend(value.ip().octets()),
        SocketAddr::V6(value) => byte_buffer.extend(value.ip().octets()),
    };

    byte_buffer.put_i32(store_host.port() as i32);

    // 13 RECONSUMETIMES
    byte_buffer.put_i32(message_ext.reconsume_times);

    // 14 Prepared Transaction Offset
    byte_buffer.put_i64(message_ext.prepared_transaction_offset);

    // 15 BODY
    byte_buffer.put_i32(body_len as i32);
    if let Some(new_body) = new_body {
        byte_buffer.put_slice(&new_body);
    } else {
        byte_buffer.put_slice(body);
    }

    // 16 TOPIC
    byte_buffer.put_u8(topic_len as u8);
    byte_buffer.put_slice(topic);

    // 17 properties
    byte_buffer.put_i16(properties_length as i16);
    byte_buffer.put_slice(properties_bytes);

    Ok(byte_buffer.freeze())
}

pub fn encode_uniquely(message_ext: &MessageExt, need_compress: bool) -> rocketmq_error::Result<Bytes> {
    let body = message_ext
        .get_body()
        .ok_or_else(|| crate::error::invalid_argument("message body is required"))?;
    let topics = message_ext.topic().as_bytes();
    let topic_len = topics.len();
    let properties = message_properties_to_string(message_ext.get_properties());
    let properties_bytes = properties.as_bytes();
    let properties_length = properties_bytes.len();
    let sys_flag = message_ext.sys_flag;
    let born_host_length = if (sys_flag & MessageSysFlag::BORNHOST_V6_FLAG) == 0 {
        8
    } else {
        20
    };
    let new_body = if need_compress && (sys_flag & MessageSysFlag::COMPRESSED_FLAG) == MessageSysFlag::COMPRESSED_FLAG {
        let compressor = CompressorFactory::get_compressor(MessageSysFlag::try_get_compression_type(sys_flag)?);
        let compressed_body = compressor.compress(body, 5)?;
        Some(compressed_body)
    } else {
        None
    };
    let body_len = new_body.as_ref().map_or(body.len(), |b| b.len());
    let store_size = if message_ext.store_size > 0 {
        message_ext.store_size as usize
    } else {
        4 // 1 TOTALSIZE
             + 4 // 2 MAGICCODE
             + 4 // 3 BODYCRC
             + 4 // 4 QUEUEID
             + 4 // 5 FLAG
             + 8 // 6 QUEUEOFFSET
             + 8 // 7 PHYSICALOFFSET
             + 4 // 8 SYSFLAG
             + 8 // 9 BORNTIMESTAMP
             + born_host_length // 10 BORNHOST
             + 4 // 11 RECONSUMETIMES
             + 8 // 12 Prepared Transaction Offset
             + 4 + body_len // 13 BODY
             + 1 + topic_len // 14 TOPIC
             + 2 + properties_length // 15 propertiesLength
    };
    let capacity = if message_ext.store_size > 0 {
        store_size.saturating_sub(8)
    } else {
        store_size
    };
    let mut byte_buffer = BytesMut::with_capacity(capacity);

    // 1 TOTALSIZE
    byte_buffer.put_i32(store_size as i32);

    // 2 MAGICCODE
    byte_buffer.put_i32(MESSAGE_MAGIC_CODE);

    // 3 BODYCRC
    byte_buffer.put_u32(message_ext.body_crc);

    // 4 QUEUEID
    byte_buffer.put_i32(message_ext.queue_id);

    // 5 FLAG
    byte_buffer.put_i32(message_ext.message.flag());

    // 6 QUEUEOFFSET
    byte_buffer.put_i64(message_ext.queue_offset);

    // 7 PHYSICALOFFSET
    byte_buffer.put_i64(message_ext.commit_log_offset);

    // 8 SYSFLAG
    byte_buffer.put_i32(message_ext.sys_flag);

    // 9 BORNTIMESTAMP
    byte_buffer.put_i64(message_ext.born_timestamp);

    // 10 BORNHOST

    let born_host = message_ext.born_host;
    match born_host {
        SocketAddr::V4(value) => byte_buffer.extend(value.ip().octets()),
        SocketAddr::V6(value) => byte_buffer.extend(value.ip().octets()),
    };
    byte_buffer.put_i32(born_host.port() as i32);

    // 11 RECONSUMETIMES
    byte_buffer.put_i32(message_ext.reconsume_times);

    // 12 Prepared Transaction Offset
    byte_buffer.put_i64(message_ext.prepared_transaction_offset);

    // 13 BODY
    byte_buffer.put_i32(body_len as i32);
    if let Some(new_body) = new_body {
        byte_buffer.put_slice(&new_body);
    } else {
        byte_buffer.put_slice(body);
    }

    // 14 TOPIC
    byte_buffer.put_i16(topic_len as i16);
    byte_buffer.put_slice(topics);

    // 15 properties
    byte_buffer.put_i16(properties_length as i16);
    byte_buffer.put_slice(properties_bytes);

    Ok(byte_buffer.freeze())
}

pub fn create_crc32(mut input: &mut [u8], crc32: u32) {
    input.put(MessageConst::PROPERTY_CRC32.as_bytes());
    input.put_u8(NAME_VALUE_SEPARATOR as u8);
    let mut crc32 = crc32;
    for _ in 0..10 {
        let mut b = b'0';
        if crc32 > 0 {
            b += (crc32 % 10) as u8;
            crc32 /= 10;
        }
        input.put_u8(b);
    }
    input.put_u8(PROPERTY_SEPARATOR as u8);
}

/// Reads the properties of the first CommitLog record. On success the input cursor points to
/// that record's topic, even if additional records follow.
pub fn decode_properties(bytes: &mut Bytes) -> Option<HashMap<CheetahString, CheetahString>> {
    let frame_size = usize::try_from(i32::from_be_bytes(*bytes.first_chunk()?)).ok()?;
    if frame_size < SYSFLAG_POSITION + 4 || frame_size > bytes.len() {
        return None;
    }

    // Read sysFlag and magicCode using fixed positions.
    let sys_flag = BigEndian::read_i32(&bytes[SYSFLAG_POSITION..SYSFLAG_POSITION + 4]);
    let magic_code = BigEndian::read_i32(&bytes[MESSAGE_MAGIC_CODE_POSITION..MESSAGE_MAGIC_CODE_POSITION + 4]);
    let version = match MessageVersion::value_of_magic_code(magic_code) {
        Ok(value) => value,
        Err(_) => return None,
    };

    // Determine address lengths.
    let bornhost_length = if (sys_flag & MessageSysFlag::BORNHOST_V6_FLAG) == 0 {
        8
    } else {
        20
    };
    let storehost_address_length = if (sys_flag & MessageSysFlag::STOREHOSTADDRESS_V6_FLAG) == 0 {
        8
    } else {
        20
    };

    // Calculate the bodySizePosition as in Java.
    let body_size_position = 4   // TOTALSIZE
        + 4   // MAGICCODE
        + 4   // BODYCRC
        + 4   // QUEUEID
        + 4   // FLAG
        + 8   // QUEUEOFFSET
        + 8   // PHYSICALOFFSET
        + 4   // SYSFLAG
        + 8   // BORNTIMESTAMP
        + bornhost_length // BORNHOST
        + 8   // STORETIMESTAMP
        + storehost_address_length // STOREHOSTADDRESS
        + 4   // RECONSUMETIMES
        + 8; // Prepared Transaction Offset

    if frame_size < body_size_position + 4 {
        return None;
    }

    // Read the body size stored as an int.
    let body_size = usize::try_from(BigEndian::read_i32(&bytes[body_size_position..body_size_position + 4])).ok()?;
    let topic_length_position = body_size_position + 4 + body_size;
    let topic_and_properties_size = frame_size.checked_sub(topic_length_position + version.get_topic_length_size())?;
    bytes.advance(topic_length_position);
    let topic_length = version.get_topic_length(bytes);

    // The cursor now points to the topic, followed by the properties length and payload.
    let (length, properties) = bytes
        .get(topic_length..topic_and_properties_size)?
        .split_first_chunk::<2>()?;
    let length = usize::try_from(i16::from_be_bytes(*length)).ok()?;
    if length == 0 {
        return None;
    }
    let text = str::from_utf8(properties.get(..length)?).ok()?;
    Some(str_to_message_properties(Some(text)))
}

#[cfg(test)]
mod tests {
    use bytes::BufMut;
    use bytes::BytesMut;

    use super::*;

    fn message_ext_with_tag(queue_offset: i64, tag: &str, body_size: usize) -> MessageExt {
        let message = Message::builder()
            .topic("MetadataFilterTopic")
            .tags(tag)
            .body(vec![b'x'; body_size])
            .build()
            .expect("test message should build");

        let mut message_ext = MessageExt::default();
        message_ext.set_message_inner(message);
        message_ext.set_queue_id(1);
        message_ext.set_queue_offset(queue_offset);
        message_ext.set_commit_log_offset(queue_offset * 1024);
        message_ext
    }

    #[test]
    fn encode_messages_matches_concatenated_single_message_wire_bytes() {
        let messages = vec![
            Message::builder()
                .topic("BatchTopic")
                .tags("TagA")
                .body_slice(b"first")
                .build_unchecked(),
            Message::builder()
                .topic("BatchTopic")
                .keys(vec!["key-a".to_string(), "key-b".to_string()])
                .body_slice(b"second-message")
                .build_unchecked(),
        ];
        let mut expected = BytesMut::new();
        for message in &messages {
            expected.put_slice(&encode_message(message));
        }

        assert_eq!(encode_messages(&messages), expected.freeze());
    }

    #[test]
    fn client_batch_reuses_adjacent_long_topics_and_rejects_invalid_topic_bytes() {
        let first = "%RETRY%payments-long-consumer-group-a";
        let second = "%RETRY%payments-long-consumer-group-b";
        let topics = [first, first, second, second];
        let mut payload = BytesMut::new();
        let mut source = message_ext_with_tag(0, "Tag", 8);
        for topic in topics {
            source.set_topic(CheetahString::from_slice(topic));
            payload.put_slice(&encode(&source, false).unwrap());
        }
        let mut invalid = encode(&source, false).unwrap().to_vec();
        let pos = invalid
            .windows(second.len())
            .position(|bytes| bytes == second.as_bytes())
            .unwrap();
        invalid[pos + second.len() - 1] = 0xff;
        payload.put_slice(&invalid);

        let messages = decode_client_batch(&mut payload.freeze(), true, false);
        assert_eq!(
            messages.iter().map(|msg| msg.topic().as_str()).collect::<Vec<_>>(),
            topics
        );
        assert_eq!(messages[0].topic().as_ptr(), messages[1].topic().as_ptr());
        assert_eq!(messages[2].topic().as_ptr(), messages[3].topic().as_ptr());
    }

    #[test]
    fn client_properties_share_only_a_retained_wire_body() {
        use std::sync::Arc;

        for (is_client, read_body, compressed, size, shares) in [
            (true, true, false, 32, true),
            (false, true, false, 32, false),
            (true, false, false, 32, false),
            (true, true, true, 32, false),
            (true, true, false, 0, false),
        ] {
            let mut source = message_ext_with_tag(0, "a-long-tag-for-the-frame-lifetime-test", size);
            if compressed {
                source.set_sys_flag(MessageSysFlag::COMPRESSED_FLAG | MessageSysFlag::COMPRESSION_ZSTD_TYPE);
            }
            let wire: Arc<[u8]> = Arc::from(encode(&source, compressed).unwrap().as_ref());
            let range = wire.as_ptr_range();
            let owner = Arc::downgrade(&wire);
            let mut input = Bytes::from_owner(wire);
            let mut message = decode(&mut input, read_body, true, is_client, false, false).unwrap();
            drop(input);
            let tag = message.message.properties().get_str("TAGS").unwrap();
            assert_eq!(tag, "a-long-tag-for-the-frame-lifetime-test");
            assert_eq!(range.contains(&tag.as_ptr()), shares);
            let mut cached = message.message.properties().clone();
            cached.detach_from_frame();
            assert_eq!(cached.get_str("TAGS"), Some(tag));
            drop(message.message.take_body());
            assert!(owner.upgrade().is_none());
            assert_eq!(
                message.message.properties().get_str("TAGS"),
                Some("a-long-tag-for-the-frame-lifetime-test")
            );
            drop(message);
            assert!(owner.upgrade().is_none());
            assert_eq!(cached.get_str("TAGS"), Some("a-long-tag-for-the-frame-lifetime-test"));
        }
    }

    #[test]
    fn decodes_batch_with_metadata_filter_skips_bodies_for_rejected_frames() {
        let rejected = message_ext_with_tag(0, "Skip", 1024);
        let accepted = message_ext_with_tag(1, "Keep", 32);
        let mut payload = BytesMut::new();
        payload.put_slice(&encode(&rejected, false).expect("rejected message should encode"));
        payload.put_slice(&encode(&accepted, false).expect("accepted message should encode"));
        let mut payload = payload.freeze();
        let mut inspected = Vec::new();

        let messages = decodes_batch_with_metadata_filter(&mut payload, true, false, |metadata| {
            inspected.push((metadata.queue_offset, metadata.get_body().is_some(), metadata.tags()));
            metadata.tags().as_deref() == Some("Keep")
        });

        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].queue_offset, 1);
        assert_eq!(
            messages[0].get_body().expect("accepted body should materialize").len(),
            32
        );
        assert_eq!(payload.len(), 0);
        assert_eq!(inspected.len(), 2);
        assert_eq!(inspected[0], (0, false, Some(CheetahString::from_static_str("Skip"))));
        assert_eq!(inspected[1], (1, false, Some(CheetahString::from_static_str("Keep"))));
    }

    #[test]
    fn metadata_filter_decompresses_only_accepted_frames_like_a_plain_decode() {
        let mut payload = BytesMut::new();
        let mut accepted_wire = BytesMut::new();
        for (queue_offset, tag) in [(0, "Skip"), (1, "Keep"), (2, "Skip"), (3, "Keep")] {
            let mut message = message_ext_with_tag(queue_offset, tag, 256);
            message.set_sys_flag(MessageSysFlag::COMPRESSED_FLAG | MessageSysFlag::COMPRESSION_ZSTD_TYPE);
            let encoded = encode(&message, true).expect("compressed message should encode");
            payload.put_slice(&encoded);
            if tag == "Keep" {
                accepted_wire.put_slice(&encoded);
            }
        }
        let mut payload = payload.freeze();
        let mut accepted_wire = accepted_wire.freeze();

        let filtered = decodes_batch_with_metadata_filter(&mut payload, true, true, |metadata| {
            metadata.tags().as_deref() == Some("Keep")
        });
        let expected = decodes_batch(&mut accepted_wire, true, true);

        assert_eq!(filtered.len(), 2);
        assert_eq!(payload.len(), 0);
        for (decoded, reference) in filtered.iter().zip(&expected) {
            assert_eq!(decoded.queue_offset(), reference.queue_offset());
            assert_eq!(decoded.get_body(), reference.get_body());
            assert_eq!(
                decoded.get_body().map(Bytes::len),
                Some(256),
                "the accepted body is decompressed"
            );
            assert_eq!(decoded.msg_id(), reference.msg_id());
            assert_eq!(decoded.get_properties(), reference.get_properties());
            assert_eq!(decoded.sys_flag(), reference.sys_flag());
        }
    }

    #[test]
    fn metadata_filter_shares_the_reply_frame_with_accepted_wire_bodies() {
        use std::sync::Arc;

        let topic = "%RETRY%payments-long-consumer-group-a";
        let mut payload = BytesMut::new();
        for (queue_offset, tag) in [(0, "Skip"), (1, "Keep"), (2, "Skip"), (3, "Keep")] {
            let mut message = message_ext_with_tag(queue_offset, tag, 32);
            message.set_topic(CheetahString::from_slice(topic));
            payload.put_slice(&encode(&message, false).expect("message should encode"));
        }
        let wire: Arc<[u8]> = Arc::from(payload.as_ref());
        let range = wire.as_ptr_range();
        let owner = Arc::downgrade(&wire);
        let mut input = Bytes::from_owner(wire);

        let messages = decodes_batch_with_metadata_filter(&mut input, true, false, |metadata| {
            assert!(metadata.get_body().is_none(), "the filter sees metadata only");
            metadata.tags().as_deref() == Some("Keep")
        });
        drop(input);

        assert_eq!(
            messages.iter().map(|message| message.queue_offset).collect::<Vec<_>>(),
            [1, 3]
        );
        for message in &messages {
            assert_eq!(message.get_body().map(Bytes::len), Some(32));
            assert_eq!(message.topic().as_str(), topic);
            let tag = message.message.properties().get_str("TAGS").expect("tag should decode");
            assert_eq!(tag, "Keep");
            assert!(
                range.contains(&tag.as_ptr()),
                "accepted properties share the reply frame"
            );
        }
        assert_eq!(messages[0].topic().as_ptr(), messages[1].topic().as_ptr());
        drop(messages);
        assert!(
            owner.upgrade().is_none(),
            "rejected and dropped messages release the reply frame"
        );
    }

    #[test]
    fn message_properties_to_string_preserves_separator_format() {
        let mut properties = HashMap::new();
        properties.insert(
            CheetahString::from_static_str("key"),
            CheetahString::from_static_str("value"),
        );

        let encoded = message_properties_to_string(&properties);

        assert_eq!(encoded, "key\u{0001}value\u{0002}");
    }

    #[test]
    fn message_properties_to_string_empty_properties_returns_empty_string() {
        let properties = HashMap::new();

        let encoded = message_properties_to_string(&properties);

        assert!(encoded.is_empty());
    }

    #[test]
    fn message_properties_to_string_round_trips_small_property_map() {
        let properties = [
            ("topic", "benchmark-topic"),
            ("keys", "key-a"),
            ("tags", "tag-a"),
            ("trace", "trace-001"),
        ]
        .into_iter()
        .map(|(key, value)| {
            (
                CheetahString::from_static_str(key),
                CheetahString::from_static_str(value),
            )
        })
        .collect::<HashMap<_, _>>();

        let encoded = message_properties_to_string(&properties);
        let decoded = string_to_message_properties(Some(&encoded));

        assert_eq!(decoded, properties);
    }

    #[test]
    fn string_and_str_property_decoders_share_behavior() {
        let encoded =
            CheetahString::from_static_str("valid\u{0001}value\u{0002}empty\u{0001}\u{0002}next\u{0001}two\u{0002}");

        let from_cheetah = string_to_message_properties(Some(&encoded));
        let from_str = str_to_message_properties(Some(encoded.as_str()));

        assert_eq!(from_cheetah, from_str);
        assert_eq!(from_cheetah.len(), 2);
    }

    #[test]
    fn str_to_message_properties_ignores_empty_and_malformed_segments() {
        let encoded = concat!(
            "valid\u{0001}value\u{0002}",
            "\u{0002}",
            "empty_value\u{0001}\u{0002}",
            "missing_separator\u{0002}",
            "second\u{0001}two\u{0002}"
        );

        let decoded = str_to_message_properties(Some(encoded));

        assert_eq!(decoded.len(), 2);
        assert_eq!(decoded.get("valid").map(CheetahString::as_str), Some("value"));
        assert_eq!(decoded.get("second").map(CheetahString::as_str), Some("two"));
    }

    #[test]
    fn property_maps_are_sized_for_their_pairs_and_the_requested_additional_entries() {
        let encoded = "a\u{0001}1\u{0002}b\u{0001}2\u{0002}";
        let decoded = str_to_message_properties_with_additional(Some(encoded), 3);
        assert_eq!(decoded.len(), 2);
        assert!(decoded.capacity() >= 5, "capacity {}", decoded.capacity());
        assert_eq!(decoded, str_to_message_properties(Some(encoded)));

        let absent = string_to_message_properties_with_additional(None, 2);
        assert!(absent.is_empty());
        assert!(absent.capacity() >= 2);
    }

    #[test]
    fn decode_messages_rejects_invalid_utf8_properties() {
        let mut bytes = BytesMut::new();
        let store_size = 4 // TOTALSIZE
            + 4 // MAGICCODE
            + 4 // BODYCRC
            + 4 // FLAG
            + 4 // BODY LENGTH
            + 2 // PROPERTIES LENGTH
            + 1; // INVALID PROPERTY BYTE

        bytes.put_i32(store_size);
        bytes.put_i32(0);
        bytes.put_i32(0);
        bytes.put_i32(0);
        bytes.put_i32(0);
        bytes.put_i16(1);
        bytes.put_u8(0xff);

        let mut bytes = bytes.freeze();

        assert!(decode_messages(&mut bytes).is_empty());
    }

    #[test]
    fn cheetah_from_utf8_lossy_borrows_valid_utf8() {
        let encoded = b"key\x01value\x02";

        let decoded = cheetah_from_utf8_lossy(encoded);

        assert_eq!(decoded, "key\u{0001}value\u{0002}");
    }

    #[test]
    fn cheetah_from_utf8_lossy_preserves_lossy_invalid_utf8_behavior() {
        let encoded = b"key\x01\xff\x02";

        let decoded = cheetah_from_utf8_lossy(encoded);

        assert_eq!(decoded.as_str(), String::from_utf8_lossy(encoded).as_ref());
    }

    #[test]
    fn count_inner_msg_num_counts_correctly_for_multiple_messages() {
        let mut bytes = BytesMut::new();
        bytes.put_i32(8);
        bytes.put_slice(&[0, 0, 0, 0]);
        bytes.put_i32(8);
        bytes.put_slice(&[0, 0, 0, 0]);
        assert_eq!(count_inner_msg_num(Some(bytes.freeze())), 2);
    }

    #[test]
    fn count_inner_msg_num_counts_correctly_for_single_message() {
        let mut bytes = BytesMut::new();
        bytes.put_i32(8);
        bytes.put_slice(&[0, 0, 0, 0]);
        assert_eq!(count_inner_msg_num(Some(bytes.freeze())), 1);
    }

    #[test]
    fn count_inner_msg_num_counts_zero_for_no_messages() {
        let bytes = BytesMut::new();
        assert_eq!(count_inner_msg_num(Some(bytes.freeze())), 0);
    }

    #[test]
    fn count_inner_msg_num_ignores_incomplete_messages() {
        let mut bytes = BytesMut::new();
        bytes.put_i32(4);
        assert_eq!(count_inner_msg_num(Some(bytes.freeze())), 1);
    }

    #[test]
    fn decode_message_id_ipv4() {
        let msg_id = "7F0000010007D8260BF075769D36C348";
        let message_id = decode_message_id(msg_id).unwrap();
        assert_eq!(message_id.address, "127.0.0.1:55334".parse().unwrap());
        assert_eq!(message_id.offset, 860316681131967304);
    }

    #[test]
    fn encode_with_compression() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from("Hello, World!"));
        let result = encode(&message_ext, true);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_with_unknown_compression_type_returns_error() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from_static(b"Hello, World!"));
        message_ext.set_sys_flag(MessageSysFlag::COMPRESSED_FLAG | (0x7 << 8));

        let result = encode(&message_ext, true);

        assert!(result.is_err());
    }

    #[test]
    fn decode_compressed_body_uses_sys_flag_compression_type() {
        let body = Bytes::from_static(b"Hello from compressed RocketMQ body");

        for compression_flag in [
            MessageSysFlag::COMPRESSION_LZ4_TYPE,
            MessageSysFlag::COMPRESSION_ZSTD_TYPE,
            MessageSysFlag::COMPRESSION_ZLIB_TYPE,
        ] {
            let mut message_ext = MessageExt::default();
            message_ext.set_body(body.clone());
            message_ext.set_sys_flag(MessageSysFlag::COMPRESSED_FLAG | compression_flag);
            let mut encoded = encode(&message_ext, true).expect("compressed message should encode");

            let decoded =
                decode(&mut encoded, true, true, false, false, false).expect("compressed message should decode");

            assert_eq!(decoded.get_body(), Some(&body));
        }
    }

    #[test]
    fn lazily_decoded_properties_match_the_eager_frame_decoder() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from_static(b"body"));
        message_ext.put_property(
            CheetahString::from_static_str("TAGS"),
            CheetahString::from_static_str("tag-a"),
        );
        message_ext.put_property(
            CheetahString::from_static_str("KEYS"),
            CheetahString::from_static_str("k1 k2"),
        );
        message_ext.put_property(
            CheetahString::from_static_str("UNIQ_KEY"),
            CheetahString::from_static_str("0A0B0C"),
        );
        let encoded = encode(&message_ext, false).expect("message should encode");

        let eager = crate::protocol::body::message_codec::decode_message_frame(&mut encoded.clone())
            .expect("frame should decode");
        for set_properties_string in [false, true] {
            let mut lazy_bytes = encoded.clone();
            let mut lazy = decode(&mut lazy_bytes, true, false, false, set_properties_string, false)
                .expect("message should decode");
            assert_eq!(lazy.get_tags(), Some(CheetahString::from_static_str("tag-a")));
            lazy.put_property(
                CheetahString::from_static_str("MIN_OFFSET"),
                CheetahString::from_static_str("3"),
            );

            let mut expected = eager.properties.clone();
            if set_properties_string {
                expected.insert(
                    CheetahString::from_static_str("propertiesString"),
                    eager.properties_string.clone(),
                );
            }
            expected.insert(
                CheetahString::from_static_str("MIN_OFFSET"),
                CheetahString::from_static_str("3"),
            );
            assert_eq!(lazy.properties(), &expected);
        }
    }

    #[test]
    fn encode_without_compression() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from("Hello, World!"));
        let result = encode(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_with_empty_body() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::new());
        let result = encode(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_with_large_body() {
        let mut message_ext = MessageExt::default();
        let large_body = vec![0u8; 1024 * 1024];
        message_ext.set_body(Bytes::from(large_body));
        let result = encode(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_uniquely_with_compression() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from("Hello, World!"));
        let result = encode_uniquely(&message_ext, true);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_uniquely_without_compression() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::from("Hello, World!"));
        let result = encode_uniquely(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_uniquely_with_empty_body() {
        let mut message_ext = MessageExt::default();
        message_ext.set_body(Bytes::new());
        let result = encode_uniquely(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn encode_uniquely_with_large_body() {
        let mut message_ext = MessageExt::default();
        let large_body = vec![0u8; 1024 * 1024];
        message_ext.set_body(Bytes::from(large_body));
        let result = encode_uniquely(&message_ext, false);
        assert!(result.is_ok());
        let bytes = result.unwrap();
        assert!(!bytes.is_empty());
    }

    // With two IPv4 hosts and an empty body, the V1 topic-length byte is at offset 88.
    const EMPTY_BODY_TOPIC_LENGTH_OFFSET: usize = 88;

    fn partial_properties_frame(size: usize, magic: i32) -> Bytes {
        let mut frame = BytesMut::zeroed(size);
        frame[..4].copy_from_slice(&(size as i32).to_be_bytes());
        frame[4..8].copy_from_slice(&magic.to_be_bytes());
        frame.freeze()
    }

    #[test]
    fn decode_properties_returns_none_if_bytes_length_is_insufficient() {
        let mut bytes = partial_properties_frame(SYSFLAG_POSITION + 3, MESSAGE_MAGIC_CODE);
        assert!(decode_properties(&mut bytes).is_none());
    }

    #[test]
    fn decode_properties_returns_none_if_magic_code_is_invalid() {
        let mut bytes = partial_properties_frame(SYSFLAG_POSITION + 4, -1);
        assert!(decode_properties(&mut bytes).is_none());
    }

    #[test]
    fn decode_properties_returns_none_if_body_size_is_insufficient() {
        let mut bytes = partial_properties_frame(EMPTY_BODY_TOPIC_LENGTH_OFFSET - 1, MESSAGE_MAGIC_CODE);
        assert!(decode_properties(&mut bytes).is_none());
    }

    #[test]
    fn decode_properties_returns_none_if_topic_length_is_insufficient() {
        let mut bytes = partial_properties_frame(EMPTY_BODY_TOPIC_LENGTH_OFFSET, MESSAGE_MAGIC_CODE);
        assert!(decode_properties(&mut bytes).is_none());
    }

    #[test]
    fn decode_properties_returns_none_if_properties_length_is_insufficient() {
        // One byte for the empty topic's length and only one byte for the two-byte properties length.
        let mut bytes = partial_properties_frame(EMPTY_BODY_TOPIC_LENGTH_OFFSET + 2, MESSAGE_MAGIC_CODE);
        assert!(decode_properties(&mut bytes).is_none());
    }

    #[test]
    fn validate_message_id_ipv4_32_chars() {
        let result = validate_message_id("AC11000100002A9F0000000000000001");
        assert!(result.is_ok());
    }

    #[test]
    fn validate_message_id_ipv6_56_chars() {
        let result = validate_message_id("20010db800000000000000000000000100002A9F0000000000000001");
        assert!(result.is_ok());
    }

    #[test]
    fn validate_message_id_ipv6_40_chars_rejected() {
        let result = validate_message_id("20010db800000000000000000000000100000001");
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("Invalid message ID length"));
            assert!(e.contains("56 characters (IPv6)"));
        }
    }

    #[test]
    fn decode_message_id_ipv6() {
        let msg_id = "20010db800000000000000000000000100002A9F0000000000000001";
        let message_id = decode_message_id(msg_id).unwrap();
        assert_eq!(message_id.address, "[2001:db8::1]:10911".parse().unwrap());
        assert_eq!(message_id.offset, 1);
    }

    #[test]
    fn decode_message_id_accepts_surrounding_whitespace() {
        for id in [
            "AC11000100002A9F0000000000000001",
            "20010db81234567800000000abcdef0100002A9F0000000000001234",
        ] {
            let padded = format!(" \t{id}\n");
            let expected = decode_message_id(id).unwrap();
            let actual = decode_message_id(&padded).unwrap();
            assert_eq!(actual.address, expected.address);
            assert_eq!(actual.offset, expected.offset);
        }
    }

    #[test]
    fn decode_message_id_ipv6_full_address() {
        let msg_id = "20010db81234567800000000abcdef0100002A9F0000000000001234";
        let message_id = decode_message_id(msg_id).unwrap();
        assert_eq!(
            message_id.address,
            "[2001:db8:1234:5678::abcd:ef01]:10911".parse().unwrap()
        );
        assert_eq!(message_id.offset, 4660);
    }
}