ek-ctp 0.12.3

CTP gateway for the enkeep ek ecosystem: MD/TD session drivers mapping CTP wire rows onto ek-data objects over the ek-event bus (pure-logic core; the CTP SDK ships inside this package and native bridging lands behind the optional `native` feature).
Documentation
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
//! CTP 结构体 ↔ 跨 ABI POD 的**字段面**(C 侧:`native/shim/ek_ctp_pod.h`)。
//!
//! ## 这一层干什么
//!
//! CTP 的 `CThostFtdc*Field` 由旧 MSVC 构建,布局是 SDK 的实现细节:Rust 侧
//! **绝不**持有它。本模块镜像 [`crate::wire`] 的 9 个结构体为纯 POD(整数 +
//! `const char*`),字段名与顺序**逐字段对应**(`wire.rs` 是唯一真源),并由
//! `ek_pod_sizeof_*` 的 `sizeof` 断言 + 逐字段自检保护。
//!
//! ## 编码(D-NATIVE-ENC)
//!
//! CTP 的 `char[]` 字段是本地码页(GBK/CP 936),跨 ABI 的字符串一律 UTF-8;
//! GBK↔UTF-8 的转换全在 shim 内(`ek_gbk_to_utf8`/`ek_utf8_to_gbk`)。
//!
//! ## 指针生命周期(读这一节再用)
//!
//! 读方向(POD 由 C 侧填充)返回的 `const char*` **指向调用方传进去的 `scratch`
//! 缓冲**,不是独立分配:scratch 必须活到 POD 被读完为止。本模块的 `to_wire`
//! 必须在同一个作用域里、scratch 还活着的时候调用。
//!
//! 写方向用 [`InputOrder::to_pod_cstr`]/[`InputOrderAction::to_pod_cstr`]:它把
//! `CString` 一起返回,由调用方持有,POD 里的指针指向它们 —— 两者必须一起存活。
//!
//! ## 纪律
//!
//! 零第三方 crate;`unsafe` 只出现在本模块的 `extern "C"` 声明与裸指针读取处。
//! Rust 2024 起 `extern` 块必须写 `unsafe extern`,这里照办。

use crate::wire::{
    DepthMarketData, ErrorField, InputOrder, InputOrderAction, InstrumentCommissionRateField,
    InstrumentField, InstrumentMarginRateField, InstrumentStatusField, InvestorPositionField,
    OrderField, QryInstrumentCommissionRate, QryInstrumentMarginRate, TradeField,
    TradingAccountField,
};
use std::ffi::{CStr, CString, c_char, c_int};

/// 读 POD 里的 `const char*` 字段;空指针 → 空串。
///
/// # Safety
///
/// 非空时必须是 NUL 结尾、且在本 POD 使用期内有效的 C 字符串(C 侧由 `scratch`
/// 保证;写方向由 `to_pod_cstr` 返回的 `CString` 保证)。
unsafe fn cstr_or_empty(p: *const c_char) -> String {
    if p.is_null() {
        String::new()
    } else {
        // SAFETY: 由本函数的 Safety 契约保证。
        unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
    }
}

/// Rust 字符串 → C 字符串(UTF-8 字节;GBK 转换在 shim 内做)。
///
/// 含内嵌 NUL 属调用方契约违背:直接 panic,**不静默截断**(截断会把下单参数悄悄
/// 变成另一个值,是不可审计的错)。与 [`super::common::cstring`] 同规矩。
fn cstring(value: &str) -> CString {
    CString::new(value)
        .unwrap_or_else(|_| panic!("ek-ctp native pod: string field contains an interior NUL byte"))
}

/* =====================================================================
 * POD 镜像(字段名与顺序 == src/wire.rs)
 *
 * 每个结构体都必须与 C 侧同名结构体逐字段一致;`size_of::<Ek*>()` 由测试
 * 断言等于 C 侧 `ek_pod_sizeof_*()`。
 * ===================================================================== */

/// `wire::ErrorField` ↔ `CThostFtdcRspInfoField`。
#[repr(C)]
pub struct EkErrorField {
    pub error_id: c_int,
    pub error_msg: *const c_char,
}

/// `wire::DepthMarketData` ↔ `CThostFtdcDepthMarketDataField`。
#[repr(C)]
pub struct EkDepthMarketData {
    pub instrument_id: *const c_char,
    /// 0.12.0(`D-XFALLBACK`):交易所码镜像。位置与 C 侧 `EkDepthMarketData` 一致
    /// (紧跟 `instrument_id`),两侧任一错位都会被 `selftest_depth` 的 k 编号抓到。
    pub exchange_id: *const c_char,
    pub last_price: f64,
    pub volume: f64,
    pub turnover: f64,
    pub open_interest: f64,
    pub upper_limit_price: f64,
    pub lower_limit_price: f64,
    pub open_price: f64,
    pub highest_price: f64,
    pub lowest_price: f64,
    pub pre_close_price: f64,
    pub bid_price1: f64,
    pub bid_price2: f64,
    pub bid_price3: f64,
    pub bid_price4: f64,
    pub bid_price5: f64,
    pub ask_price1: f64,
    pub ask_price2: f64,
    pub ask_price3: f64,
    pub ask_price4: f64,
    pub ask_price5: f64,
    pub bid_volume1: f64,
    pub bid_volume2: f64,
    pub bid_volume3: f64,
    pub bid_volume4: f64,
    pub bid_volume5: f64,
    pub ask_volume1: f64,
    pub ask_volume2: f64,
    pub ask_volume3: f64,
    pub ask_volume4: f64,
    pub ask_volume5: f64,
    pub update_time: *const c_char,
    pub update_millisec: i64,
    /// 报文 `TradingDay`(业务日权威值;记档偏差,见 DESIGN D-TZ)
    pub trading_day: *const c_char,
    pub action_day: *const c_char,
}

/// `wire::InstrumentField` ↔ `CThostFtdcInstrumentField`。
#[repr(C)]
pub struct EkInstrumentField {
    pub instrument_id: *const c_char,
    pub exchange_id: *const c_char,
    pub instrument_name: *const c_char,
    pub product_class: *const c_char,
    pub volume_multiple: f64,
    pub price_tick: f64,
    pub max_limit_order_volume: f64,
    pub min_limit_order_volume: f64,
    pub max_market_order_volume: f64,
    pub min_market_order_volume: f64,
    pub delivery_year: i64,
    pub delivery_month: i64,
    pub product_id: *const c_char,
    pub is_trading: i64,
    pub open_date: *const c_char,
}

/// `wire::OrderField` ↔ `CThostFtdcOrderField`。
#[repr(C)]
pub struct EkOrderField {
    pub instrument_id: *const c_char,
    /// 0.7.0:交易所代码随回报自带(合约表查 exchange 退役;见 wire::OrderField)。
    pub exchange_id: *const c_char,
    pub order_ref: *const c_char,
    pub front_id: i64,
    pub session_id: i64,
    pub order_sys_id: *const c_char,
    pub direction: *const c_char,
    pub comb_offset_flag: *const c_char,
    pub order_price_type: *const c_char,
    pub time_condition: *const c_char,
    pub volume_condition: *const c_char,
    pub limit_price: f64,
    pub volume_total_original: f64,
    pub volume_total: f64,
    pub volume_traded: f64,
    pub order_status: *const c_char,
    pub insert_date: *const c_char,
    pub insert_time: *const c_char,
}

/// `wire::TradeField` ↔ `CThostFtdcTradeField`。
#[repr(C)]
pub struct EkTradeField {
    pub instrument_id: *const c_char,
    /// 0.7.0:同 [`Self` 的 `exchange_id` 语义](同 EkOrderField)。
    pub exchange_id: *const c_char,
    pub order_sys_id: *const c_char,
    pub trade_id: *const c_char,
    pub direction: *const c_char,
    pub offset_flag: *const c_char,
    pub price: f64,
    pub volume: f64,
    pub trade_date: *const c_char,
    pub trade_time: *const c_char,
}

/// `wire::InvestorPositionField` ↔ `CThostFtdcInvestorPositionField`。
#[repr(C)]
pub struct EkInvestorPositionField {
    pub instrument_id: *const c_char,
    /// 0.7.0:同 EkOrderField.exchange_id。
    pub exchange_id: *const c_char,
    pub posi_direction: *const c_char,
    pub yd_position: f64,
    pub position: f64,
    pub today_position: f64,
    pub position_cost: f64,
    pub position_profit: f64,
    pub short_frozen: f64,
    pub long_frozen: f64,
}

/// `wire::TradingAccountField` ↔ `CThostFtdcTradingAccountField`。
#[repr(C)]
pub struct EkTradingAccountField {
    pub account_id: *const c_char,
    pub balance: f64,
    pub frozen_margin: f64,
    pub frozen_cash: f64,
    pub frozen_commission: f64,
    pub available: f64,
}

/// `wire::InputOrder` ↔ `CThostFtdcInputOrderField`。
#[repr(C)]
pub struct EkInputOrder {
    pub instrument_id: *const c_char,
    pub exchange_id: *const c_char,
    pub limit_price: f64,
    pub volume_total_original: i64,
    pub order_price_type: *const c_char,
    pub direction: *const c_char,
    pub comb_offset_flag: *const c_char,
    pub order_ref: *const c_char,
    pub investor_id: *const c_char,
    pub user_id: *const c_char,
    pub broker_id: *const c_char,
    pub comb_hedge_flag: *const c_char,
    pub contingent_condition: *const c_char,
    pub force_close_reason: *const c_char,
    pub is_auto_suspend: c_int,
    pub time_condition: *const c_char,
    pub volume_condition: *const c_char,
    pub min_volume: i64,
}

/// `wire::InputOrderAction` ↔ `CThostFtdcInputOrderActionField`。
#[repr(C)]
pub struct EkInputOrderAction {
    pub instrument_id: *const c_char,
    pub exchange_id: *const c_char,
    pub order_ref: *const c_char,
    pub front_id: i64,
    pub session_id: i64,
    pub action_flag: *const c_char,
    pub broker_id: *const c_char,
    pub investor_id: *const c_char,
}

/// `wire::InstrumentMarginRateField` ↔ `CThostFtdcInstrumentMarginRateField`。
/// 附加接口面(超出原稿):保证金率查询应答镜像(reserve1 省略)。
#[repr(C)]
pub struct EkInstrumentMarginRate {
    pub investor_range: *const c_char,
    pub broker_id: *const c_char,
    pub investor_id: *const c_char,
    pub hedge_flag: *const c_char,
    pub long_margin_ratio_by_money: f64,
    pub long_margin_ratio_by_volume: f64,
    pub short_margin_ratio_by_money: f64,
    pub short_margin_ratio_by_volume: f64,
    pub is_relative: c_int,
    pub exchange_id: *const c_char,
    pub invest_unit_id: *const c_char,
    pub instrument_id: *const c_char,
}

/// `wire::InstrumentCommissionRateField` ↔ `CThostFtdcInstrumentCommissionRateField`。
/// 附加接口面(超出原稿):手续费率查询应答镜像(reserve1 省略)。
#[repr(C)]
pub struct EkInstrumentCommissionRate {
    pub investor_range: *const c_char,
    pub broker_id: *const c_char,
    pub investor_id: *const c_char,
    pub open_ratio_by_money: f64,
    pub open_ratio_by_volume: f64,
    pub close_ratio_by_money: f64,
    pub close_ratio_by_volume: f64,
    pub close_today_ratio_by_money: f64,
    pub close_today_ratio_by_volume: f64,
    pub exchange_id: *const c_char,
    pub biz_type: *const c_char,
    pub invest_unit_id: *const c_char,
    pub instrument_id: *const c_char,
}

/// `wire::InstrumentStatusField` ↔ `CThostFtdcInstrumentStatusField`。
/// 附加接口面(超出原稿):交易状态推送镜像(reserve1/2 省略)。
#[repr(C)]
pub struct EkInstrumentStatus {
    pub exchange_id: *const c_char,
    pub settlement_group_id: *const c_char,
    pub instrument_status: *const c_char,
    pub trading_segment_sn: c_int,
    pub enter_time: *const c_char,
    pub enter_reason: *const c_char,
    pub exchange_inst_id: *const c_char,
    pub instrument_id: *const c_char,
}

/// `wire::QryInstrumentMarginRate` ↔ `CThostFtdcQryInstrumentMarginRateField`。
/// 写方向输入 POD(保证金率查询,reserve1 省略)。
#[repr(C)]
pub struct EkQryInstrumentMarginRate {
    pub broker_id: *const c_char,
    pub investor_id: *const c_char,
    pub hedge_flag: *const c_char,
    pub exchange_id: *const c_char,
    pub invest_unit_id: *const c_char,
    pub instrument_id: *const c_char,
}

/// `wire::QryInstrumentCommissionRate` ↔ `CThostFtdcQryInstrumentCommissionRateField`。
/// 写方向输入 POD(手续费率查询,**无 HedgeFlag**)。
#[repr(C)]
pub struct EkQryInstrumentCommissionRate {
    pub broker_id: *const c_char,
    pub investor_id: *const c_char,
    pub exchange_id: *const c_char,
    pub invest_unit_id: *const c_char,
    pub instrument_id: *const c_char,
}

/* =====================================================================
 * C ABI 声明(签名与 native/shim/ek_ctp_pod.h 严格一致)
 *
 * CTP 结构体在 C 侧是有类型的指针;Rust 侧看不到那些类型,一律用 `*const c_void`
 * 占位 —— 指针就是指针,ABI 上等价。
 * ===================================================================== */
unsafe extern "C" {
    // ---- 编码(GBK ↔ UTF-8,CP 936)----
    fn ek_gbk_to_utf8(
        gbk: *const c_char,
        gbk_len: usize,
        out: *mut c_char,
        out_cap: usize,
    ) -> usize;
    fn ek_utf8_to_gbk(utf8: *const c_char, out: *mut c_char, out_cap: usize) -> usize;
}

// **仅验证面**:下面这些入口在业务路径里**不被 Rust 调用** —— POD 的填充与回写都发生
// 在 shim 内部(回调里把 CTP 结构填进 POD、下单时把 POD 读回 CTP 结构),Rust 只做
// `to_wire` / `to_pod_cstr`。它们导出到 C ABI,是为了让 **Rust 侧能做逐字段验证**
// (`ek_pod_selftest_*` 在 C++ 里构造带唯一值的 CTP 报文,再走真实转换函数)。
// 故整体标 `#[cfg(test)]`:非测试构建里这些声明不存在,既不占 ABI 面,也不会让人
// 误以为它们是业务接口。
#[cfg(test)]
unsafe extern "C" {
    // 注:读方向的 `ek_pod_from_*` 与写方向的 `ek_pod_to_input_order*` **不在这里声明**:
    // 业务路径里 POD 的填充与回写都由 shim 内部完成(回调里把 CTP 结构填进 POD、下单时
    // 把 POD 读回 CTP 结构),Rust 不经手;Rust 侧要验证往返时用下面的
    // `ek_pod_selftest_io_roundtrip_*`(转换在 C++ 里走真实函数)。

    // ---- sizeof 自检 ----
    fn ek_pod_sizeof_error() -> c_int;
    fn ek_pod_sizeof_depth() -> c_int;
    fn ek_pod_sizeof_instrument() -> c_int;
    fn ek_pod_sizeof_order() -> c_int;
    fn ek_pod_sizeof_trade() -> c_int;
    fn ek_pod_sizeof_position() -> c_int;
    fn ek_pod_sizeof_account() -> c_int;
    fn ek_pod_sizeof_input_order() -> c_int;
    fn ek_pod_sizeof_input_order_action() -> c_int;
    fn ek_pod_sizeof_margin_rate() -> c_int;
    fn ek_pod_sizeof_commission_rate() -> c_int;
    fn ek_pod_sizeof_instrument_status() -> c_int;
    fn ek_pod_sizeof_qry_margin_rate() -> c_int;
    fn ek_pod_sizeof_qry_commission_rate() -> c_int;

    // ---- 离线自检(在 C++ 里构造 CTP 结构,填确定值,再走真实转换)----
    fn ek_pod_selftest_error(out: *mut EkErrorField, scratch: *mut c_char, cap: usize);
    /// 0.12.0:请求路径字段的 GBK 编码自检(见 `ek_ctp_shim.h`)。
    fn ek_shim_selftest_copy_field(out: *mut c_char, cap: usize);
    /// 0.12.0:超长输入的截断路径自检。
    fn ek_shim_selftest_copy_field_truncated(out: *mut c_char, cap: usize);
    fn ek_pod_selftest_depth(out: *mut EkDepthMarketData, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_instrument(out: *mut EkInstrumentField, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_order(out: *mut EkOrderField, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_trade(out: *mut EkTradeField, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_position(
        out: *mut EkInvestorPositionField,
        scratch: *mut c_char,
        cap: usize,
    );
    fn ek_pod_selftest_account(out: *mut EkTradingAccountField, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_input_order(out: *mut EkInputOrder, scratch: *mut c_char, cap: usize);
    fn ek_pod_selftest_io_roundtrip_input_order(
        input: *const EkInputOrder,
        out: *mut EkInputOrder,
        scratch: *mut c_char,
        cap: usize,
    );
    fn ek_pod_selftest_io_roundtrip_input_order_action(
        input: *const EkInputOrderAction,
        out: *mut EkInputOrderAction,
        scratch: *mut c_char,
        cap: usize,
    );
    /// 写方向单向校验:真实转换 → 按字段名独立重建期望 → 逐字段比对。
    /// 0=全对;1..8=首个错位(序号见 shim 注释);-1=空指针。补 M2 审计
    /// 「roundtrip 成对写错会抵消」的缺口(D-NATIVE-AUDIT)。
    fn ek_ctp_verify_input_order_action(input: *const EkInputOrderAction) -> c_int;
    // ---- 附加接口面:三件(保证金率/手续费率/交易状态)的离线自检 ----
    fn ek_pod_selftest_margin_rate(
        out: *mut EkInstrumentMarginRate,
        scratch: *mut c_char,
        cap: usize,
    );
    fn ek_pod_selftest_commission_rate(
        out: *mut EkInstrumentCommissionRate,
        scratch: *mut c_char,
        cap: usize,
    );
    fn ek_pod_selftest_instrument_status(
        out: *mut EkInstrumentStatus,
        scratch: *mut c_char,
        cap: usize,
    );
    // ---- 附加接口面:两个查询输入的写方向单向校验 ----
    fn ek_ctp_verify_qry_margin_rate(input: *const EkQryInstrumentMarginRate) -> c_int;
    fn ek_ctp_verify_qry_commission_rate(input: *const EkQryInstrumentCommissionRate) -> c_int;
}

/* =====================================================================
 * 安全包装:编码
 * ===================================================================== */

/// GBK 字节 → UTF-8 字符串;非法 GBK 或超长 → 空串(shim 的降级规则)。
///
/// 需要按 CTP 字段的**固定长度**(可能没有 NUL 结尾)解码时用这个入口。
pub fn gbk_to_utf8(gbk: &[u8]) -> String {
    if gbk.is_empty() {
        return String::new();
    }
    // UTF-8 最坏展开是 3 字节/字符,输入是 GBK(≥1 字节/字符):3 * len + 1 必够。
    let mut out = vec![0u8; gbk.len() * 3 + 1];
    // SAFETY: 输入切片有效且长度显式传入;输出缓冲足够大,shim 侧还会再校验容量。
    let n = unsafe {
        ek_gbk_to_utf8(
            gbk.as_ptr() as *const c_char,
            gbk.len(),
            out.as_mut_ptr() as *mut c_char,
            out.len(),
        )
    };
    out.truncate(n.min(out.len()));
    String::from_utf8_lossy(&out).into_owned()
}

/// UTF-8 字符串 → GBK 字节;非法 UTF-8/内嵌 NUL → 空(不 panic)。
///
/// GBK 每个字符最多 2 字节,而 UTF-8 输入至少 1 字节/字符:2 * len + 1 必够。
pub fn utf8_to_gbk(text: &str) -> Vec<u8> {
    if text.is_empty() {
        return Vec::new();
    }
    let Ok(src) = CString::new(text) else {
        return Vec::new();
    };
    let mut out = vec![0u8; text.len() * 2 + 1];
    // SAFETY: src 是 NUL 结尾的 C 字符串;输出缓冲足够大。
    let n = unsafe { ek_utf8_to_gbk(src.as_ptr(), out.as_mut_ptr() as *mut c_char, out.len()) };
    out.truncate(n.min(out.len()));
    out
}

/* =====================================================================
 * 读方向:POD → wire
 *
 * 每个 `to_wire` 都是安全函数,但有一个调用方契约:POD 必须由 C 侧填充
 * (回调 / `ek_pod_selftest_*`),且字符串指针在其 `scratch` 存活期内有效。
 * ===================================================================== */

impl EkErrorField {
    /// POD → `wire::ErrorField`。
    ///
    /// 契约:POD 由 C 侧填充,`error_msg` 指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> ErrorField {
        // SAFETY: 见方法文档的调用方契约;空指针由 cstr_or_empty 兜住。
        unsafe {
            ErrorField {
                error_id: self.error_id,
                error_msg: cstr_or_empty(self.error_msg),
            }
        }
    }
}

impl EkDepthMarketData {
    /// POD → `wire::DepthMarketData`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> DepthMarketData {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            DepthMarketData {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                last_price: self.last_price,
                volume: self.volume,
                turnover: self.turnover,
                open_interest: self.open_interest,
                upper_limit_price: self.upper_limit_price,
                lower_limit_price: self.lower_limit_price,
                open_price: self.open_price,
                highest_price: self.highest_price,
                lowest_price: self.lowest_price,
                pre_close_price: self.pre_close_price,
                bid_price1: self.bid_price1,
                bid_price2: self.bid_price2,
                bid_price3: self.bid_price3,
                bid_price4: self.bid_price4,
                bid_price5: self.bid_price5,
                ask_price1: self.ask_price1,
                ask_price2: self.ask_price2,
                ask_price3: self.ask_price3,
                ask_price4: self.ask_price4,
                ask_price5: self.ask_price5,
                bid_volume1: self.bid_volume1,
                bid_volume2: self.bid_volume2,
                bid_volume3: self.bid_volume3,
                bid_volume4: self.bid_volume4,
                bid_volume5: self.bid_volume5,
                ask_volume1: self.ask_volume1,
                ask_volume2: self.ask_volume2,
                ask_volume3: self.ask_volume3,
                ask_volume4: self.ask_volume4,
                ask_volume5: self.ask_volume5,
                update_time: cstr_or_empty(self.update_time),
                update_millisec: self.update_millisec,
                trading_day: cstr_or_empty(self.trading_day),
                action_day: cstr_or_empty(self.action_day),
            }
        }
    }
}

impl EkInstrumentField {
    /// POD → `wire::InstrumentField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> InstrumentField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InstrumentField {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                instrument_name: cstr_or_empty(self.instrument_name),
                product_class: cstr_or_empty(self.product_class),
                volume_multiple: self.volume_multiple,
                price_tick: self.price_tick,
                max_limit_order_volume: self.max_limit_order_volume,
                min_limit_order_volume: self.min_limit_order_volume,
                max_market_order_volume: self.max_market_order_volume,
                min_market_order_volume: self.min_market_order_volume,
                delivery_year: self.delivery_year,
                delivery_month: self.delivery_month,
                product_id: cstr_or_empty(self.product_id),
                is_trading: self.is_trading,
                open_date: cstr_or_empty(self.open_date),
            }
        }
    }
}

impl EkOrderField {
    /// POD → `wire::OrderField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> OrderField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            OrderField {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                order_ref: cstr_or_empty(self.order_ref),
                front_id: self.front_id,
                session_id: self.session_id,
                order_sys_id: cstr_or_empty(self.order_sys_id),
                direction: cstr_or_empty(self.direction),
                comb_offset_flag: cstr_or_empty(self.comb_offset_flag),
                order_price_type: cstr_or_empty(self.order_price_type),
                time_condition: cstr_or_empty(self.time_condition),
                volume_condition: cstr_or_empty(self.volume_condition),
                limit_price: self.limit_price,
                volume_total_original: self.volume_total_original,
                volume_total: self.volume_total,
                volume_traded: self.volume_traded,
                order_status: cstr_or_empty(self.order_status),
                insert_date: cstr_or_empty(self.insert_date),
                insert_time: cstr_or_empty(self.insert_time),
            }
        }
    }
}

impl EkTradeField {
    /// POD → `wire::TradeField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> TradeField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            TradeField {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                order_sys_id: cstr_or_empty(self.order_sys_id),
                trade_id: cstr_or_empty(self.trade_id),
                direction: cstr_or_empty(self.direction),
                offset_flag: cstr_or_empty(self.offset_flag),
                price: self.price,
                volume: self.volume,
                trade_date: cstr_or_empty(self.trade_date),
                trade_time: cstr_or_empty(self.trade_time),
            }
        }
    }
}

impl EkInvestorPositionField {
    /// POD → `wire::InvestorPositionField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> InvestorPositionField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InvestorPositionField {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                posi_direction: cstr_or_empty(self.posi_direction),
                yd_position: self.yd_position,
                position: self.position,
                today_position: self.today_position,
                position_cost: self.position_cost,
                position_profit: self.position_profit,
                short_frozen: self.short_frozen,
                long_frozen: self.long_frozen,
            }
        }
    }
}

impl EkTradingAccountField {
    /// POD → `wire::TradingAccountField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> TradingAccountField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            TradingAccountField {
                account_id: cstr_or_empty(self.account_id),
                balance: self.balance,
                frozen_margin: self.frozen_margin,
                frozen_cash: self.frozen_cash,
                frozen_commission: self.frozen_commission,
                available: self.available,
            }
        }
    }
}

impl EkInputOrder {
    /// POD → `wire::InputOrder`(写方向的读回面)。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch` 或调用方持有的 `CString`。
    pub fn to_wire(&self) -> InputOrder {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InputOrder {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                limit_price: self.limit_price,
                volume_total_original: self.volume_total_original,
                order_price_type: cstr_or_empty(self.order_price_type),
                direction: cstr_or_empty(self.direction),
                comb_offset_flag: cstr_or_empty(self.comb_offset_flag),
                order_ref: cstr_or_empty(self.order_ref),
                investor_id: cstr_or_empty(self.investor_id),
                user_id: cstr_or_empty(self.user_id),
                broker_id: cstr_or_empty(self.broker_id),
                comb_hedge_flag: cstr_or_empty(self.comb_hedge_flag),
                contingent_condition: cstr_or_empty(self.contingent_condition),
                force_close_reason: cstr_or_empty(self.force_close_reason),
                is_auto_suspend: self.is_auto_suspend,
                time_condition: cstr_or_empty(self.time_condition),
                volume_condition: cstr_or_empty(self.volume_condition),
                min_volume: self.min_volume,
            }
        }
    }
}

impl EkInputOrderAction {
    /// POD → `wire::InputOrderAction`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch` 或调用方持有的 `CString`。
    pub fn to_wire(&self) -> InputOrderAction {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InputOrderAction {
                instrument_id: cstr_or_empty(self.instrument_id),
                exchange_id: cstr_or_empty(self.exchange_id),
                order_ref: cstr_or_empty(self.order_ref),
                front_id: self.front_id,
                session_id: self.session_id,
                action_flag: cstr_or_empty(self.action_flag),
                broker_id: cstr_or_empty(self.broker_id),
                investor_id: cstr_or_empty(self.investor_id),
            }
        }
    }
}

/* =====================================================================
 * 附加接口面(超出原稿):保证金率/手续费率/交易状态 读向
 * ===================================================================== */

impl EkInstrumentMarginRate {
    /// POD → `wire::InstrumentMarginRateField`。
    ///
    /// 契约:字符串指针指向仍存活的 `scratch`。
    pub fn to_wire(&self) -> InstrumentMarginRateField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InstrumentMarginRateField {
                investor_range: cstr_or_empty(self.investor_range),
                broker_id: cstr_or_empty(self.broker_id),
                investor_id: cstr_or_empty(self.investor_id),
                hedge_flag: cstr_or_empty(self.hedge_flag),
                long_margin_ratio_by_money: self.long_margin_ratio_by_money,
                long_margin_ratio_by_volume: self.long_margin_ratio_by_volume,
                short_margin_ratio_by_money: self.short_margin_ratio_by_money,
                short_margin_ratio_by_volume: self.short_margin_ratio_by_volume,
                is_relative: self.is_relative,
                exchange_id: cstr_or_empty(self.exchange_id),
                invest_unit_id: cstr_or_empty(self.invest_unit_id),
                instrument_id: cstr_or_empty(self.instrument_id),
            }
        }
    }
}

impl EkInstrumentCommissionRate {
    /// POD → `wire::InstrumentCommissionRateField`。
    pub fn to_wire(&self) -> InstrumentCommissionRateField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InstrumentCommissionRateField {
                investor_range: cstr_or_empty(self.investor_range),
                broker_id: cstr_or_empty(self.broker_id),
                investor_id: cstr_or_empty(self.investor_id),
                open_ratio_by_money: self.open_ratio_by_money,
                open_ratio_by_volume: self.open_ratio_by_volume,
                close_ratio_by_money: self.close_ratio_by_money,
                close_ratio_by_volume: self.close_ratio_by_volume,
                close_today_ratio_by_money: self.close_today_ratio_by_money,
                close_today_ratio_by_volume: self.close_today_ratio_by_volume,
                exchange_id: cstr_or_empty(self.exchange_id),
                biz_type: cstr_or_empty(self.biz_type),
                invest_unit_id: cstr_or_empty(self.invest_unit_id),
                instrument_id: cstr_or_empty(self.instrument_id),
            }
        }
    }
}

impl EkInstrumentStatus {
    /// POD → `wire::InstrumentStatusField`。
    pub fn to_wire(&self) -> InstrumentStatusField {
        // SAFETY: 见方法文档的调用方契约。
        unsafe {
            InstrumentStatusField {
                exchange_id: cstr_or_empty(self.exchange_id),
                settlement_group_id: cstr_or_empty(self.settlement_group_id),
                instrument_status: cstr_or_empty(self.instrument_status),
                trading_segment_sn: self.trading_segment_sn,
                enter_time: cstr_or_empty(self.enter_time),
                enter_reason: cstr_or_empty(self.enter_reason),
                exchange_inst_id: cstr_or_empty(self.exchange_inst_id),
                instrument_id: cstr_or_empty(self.instrument_id),
            }
        }
    }
}

/* =====================================================================
 * 写方向:wire → POD
 * ===================================================================== */
impl InputOrder {
    /// `wire::InputOrder` → POD,**连同持有字符串的 `CString` 一起返回**。
    ///
    /// 用法:POD 里的 `const char*` 指向这些 `CString` 的堆缓冲,两者必须**一起
    /// 存活** —— `Vec<CString>` 一旦 drop,POD 就是悬垂指针。
    ///
    /// ```ignore
    /// let (pod, keep) = order.to_pod_cstr();
    /// api.req_order_insert(&pod, reqid); // keep 仍在此作用域:它托着 pod 里的字符串
    /// ```
    ///
    /// (移动 `CString` 只搬结构体本身,堆缓冲地址不变,所以下面"先建 POD 再收进
    /// `Vec`"是安全的。)
    pub fn to_pod_cstr(&self) -> (EkInputOrder, Vec<CString>) {
        let instrument_id = cstring(&self.instrument_id);
        let exchange_id = cstring(&self.exchange_id);
        let order_price_type = cstring(&self.order_price_type);
        let direction = cstring(&self.direction);
        let comb_offset_flag = cstring(&self.comb_offset_flag);
        let order_ref = cstring(&self.order_ref);
        let investor_id = cstring(&self.investor_id);
        let user_id = cstring(&self.user_id);
        let broker_id = cstring(&self.broker_id);
        let comb_hedge_flag = cstring(&self.comb_hedge_flag);
        let contingent_condition = cstring(&self.contingent_condition);
        let force_close_reason = cstring(&self.force_close_reason);
        let time_condition = cstring(&self.time_condition);
        let volume_condition = cstring(&self.volume_condition);
        let pod = EkInputOrder {
            instrument_id: instrument_id.as_ptr(),
            exchange_id: exchange_id.as_ptr(),
            limit_price: self.limit_price,
            volume_total_original: self.volume_total_original,
            order_price_type: order_price_type.as_ptr(),
            direction: direction.as_ptr(),
            comb_offset_flag: comb_offset_flag.as_ptr(),
            order_ref: order_ref.as_ptr(),
            investor_id: investor_id.as_ptr(),
            user_id: user_id.as_ptr(),
            broker_id: broker_id.as_ptr(),
            comb_hedge_flag: comb_hedge_flag.as_ptr(),
            contingent_condition: contingent_condition.as_ptr(),
            force_close_reason: force_close_reason.as_ptr(),
            is_auto_suspend: self.is_auto_suspend,
            time_condition: time_condition.as_ptr(),
            volume_condition: volume_condition.as_ptr(),
            min_volume: self.min_volume,
        };
        let keep = vec![
            instrument_id,
            exchange_id,
            order_price_type,
            direction,
            comb_offset_flag,
            order_ref,
            investor_id,
            user_id,
            broker_id,
            comb_hedge_flag,
            contingent_condition,
            force_close_reason,
            time_condition,
            volume_condition,
        ];
        (pod, keep)
    }
}

impl InputOrderAction {
    /// `wire::InputOrderAction` → POD,连同持有字符串的 `CString` 一起返回。
    ///
    /// 生命周期规则与 [`InputOrder::to_pod_cstr`] 相同:POD 与返回的 `Vec` 必须
    /// 一起存活。
    pub fn to_pod_cstr(&self) -> (EkInputOrderAction, Vec<CString>) {
        let instrument_id = cstring(&self.instrument_id);
        let exchange_id = cstring(&self.exchange_id);
        let order_ref = cstring(&self.order_ref);
        let action_flag = cstring(&self.action_flag);
        let broker_id = cstring(&self.broker_id);
        let investor_id = cstring(&self.investor_id);
        let pod = EkInputOrderAction {
            instrument_id: instrument_id.as_ptr(),
            exchange_id: exchange_id.as_ptr(),
            order_ref: order_ref.as_ptr(),
            front_id: self.front_id,
            session_id: self.session_id,
            action_flag: action_flag.as_ptr(),
            broker_id: broker_id.as_ptr(),
            investor_id: investor_id.as_ptr(),
        };
        let keep = vec![
            instrument_id,
            exchange_id,
            order_ref,
            action_flag,
            broker_id,
            investor_id,
        ];
        (pod, keep)
    }
}

/* =====================================================================
 * 写方向:两个查询输入(保证金率/手续费率)同样 wire → POD
 * ===================================================================== */

impl QryInstrumentMarginRate {
    /// `wire::QryInstrumentMarginRate` → POD,连同持有字符串的 `CString` 一起返回。
    ///
    /// 生命周期规则与 [`InputOrder::to_pod_cstr`] 相同:POD 与返回的 `Vec` 必须
    /// 一起存活;Req 面在 shim 内把 POD 写回 `CThostFtdcQryInstrumentMarginRateField`。
    pub fn to_pod_cstr(&self) -> (EkQryInstrumentMarginRate, Vec<CString>) {
        let broker_id = cstring(&self.broker_id);
        let investor_id = cstring(&self.investor_id);
        let hedge_flag = cstring(&self.hedge_flag);
        let exchange_id = cstring(&self.exchange_id);
        let invest_unit_id = cstring(&self.invest_unit_id);
        let instrument_id = cstring(&self.instrument_id);
        let pod = EkQryInstrumentMarginRate {
            broker_id: broker_id.as_ptr(),
            investor_id: investor_id.as_ptr(),
            hedge_flag: hedge_flag.as_ptr(),
            exchange_id: exchange_id.as_ptr(),
            invest_unit_id: invest_unit_id.as_ptr(),
            instrument_id: instrument_id.as_ptr(),
        };
        let keep = vec![
            broker_id,
            investor_id,
            hedge_flag,
            exchange_id,
            invest_unit_id,
            instrument_id,
        ];
        (pod, keep)
    }
}

impl QryInstrumentCommissionRate {
    /// `wire::QryInstrumentCommissionRate` → POD(CG 同上;**无 HedgeFlag**)。
    pub fn to_pod_cstr(&self) -> (EkQryInstrumentCommissionRate, Vec<CString>) {
        let broker_id = cstring(&self.broker_id);
        let investor_id = cstring(&self.investor_id);
        let exchange_id = cstring(&self.exchange_id);
        let invest_unit_id = cstring(&self.invest_unit_id);
        let instrument_id = cstring(&self.instrument_id);
        let pod = EkQryInstrumentCommissionRate {
            broker_id: broker_id.as_ptr(),
            investor_id: investor_id.as_ptr(),
            exchange_id: exchange_id.as_ptr(),
            invest_unit_id: invest_unit_id.as_ptr(),
            instrument_id: instrument_id.as_ptr(),
        };
        let keep = vec![
            broker_id,
            investor_id,
            exchange_id,
            invest_unit_id,
            instrument_id,
        ];
        (pod, keep)
    }
}

/* =====================================================================
 * 测试(离线验收核心)
 *
 * 计数规则(与 C++ 侧 `ek_pod_selftest_*` 完全一致):按 `wire.rs` 声明顺序,
 * k 从 1 起逐字段 +1;f64 → k、i64 → 1000+k、i32 → 2000+k、String → "s<k>";
 * 落在 CTP **标量 char** 上的 String → 'A' + (k % 26)。
 *
 * 断言按 wire 顺序逐字段写,`K` 计数器同步推进:两边的字段顺序一旦错位,
 * 值就对不上 —— 这正是本层最需要抓的错。
 * ===================================================================== */
#[cfg(test)]
mod tests {
    use super::*;

    /// 自检用的 scratch 容量(9 个 POD 里最长的是 depth:几十个短串)。
    const SCRATCH_CAP: usize = 8192;

    fn scratch() -> Vec<u8> {
        vec![0u8; SCRATCH_CAP]
    }

    /// 全零 POD(纯整数 + 裸指针,全零是合法值)。
    fn zeroed<T>() -> T {
        // SAFETY: 目标类型是 POD,全零位模式有效。
        unsafe { std::mem::zeroed() }
    }

    fn scratch_ptr(buf: &mut [u8]) -> *mut c_char {
        buf.as_mut_ptr() as *mut c_char
    }

    /// 按 wire 声明顺序推进的计数器(规则见模块测试头注释)。
    struct K(u32);

    impl K {
        fn new() -> Self {
            K(0)
        }
        fn next(&mut self) -> u32 {
            self.0 += 1;
            self.0
        }
        fn f64(&mut self) -> f64 {
            f64::from(self.next())
        }
        fn i64(&mut self) -> i64 {
            1000 + i64::from(self.next())
        }
        fn i32(&mut self) -> i32 {
            2000 + self.next() as i32
        }
        fn s(&mut self) -> String {
            format!("s{}", self.next())
        }
        /// CTP 标量 char 字段:'A' + (k % 26)。
        fn ch(&mut self) -> String {
            char::from(b'A' + (self.next() % 26) as u8).to_string()
        }
    }

    /* ---------------- (a) sizeof 断言 ---------------- */

    #[test]
    fn pod_sizeof_matches_rust_layout() {
        // SAFETY: 这些函数只返回 sizeof,无副作用。
        unsafe {
            assert_eq!(ek_pod_sizeof_error() as usize, size_of::<EkErrorField>());
            assert_eq!(
                ek_pod_sizeof_depth() as usize,
                size_of::<EkDepthMarketData>()
            );
            assert_eq!(
                ek_pod_sizeof_instrument() as usize,
                size_of::<EkInstrumentField>()
            );
            assert_eq!(ek_pod_sizeof_order() as usize, size_of::<EkOrderField>());
            assert_eq!(ek_pod_sizeof_trade() as usize, size_of::<EkTradeField>());
            assert_eq!(
                ek_pod_sizeof_position() as usize,
                size_of::<EkInvestorPositionField>()
            );
            assert_eq!(
                ek_pod_sizeof_account() as usize,
                size_of::<EkTradingAccountField>()
            );
            assert_eq!(
                ek_pod_sizeof_input_order() as usize,
                size_of::<EkInputOrder>()
            );
            assert_eq!(
                ek_pod_sizeof_input_order_action() as usize,
                size_of::<EkInputOrderAction>()
            );
            assert_eq!(
                ek_pod_sizeof_margin_rate() as usize,
                size_of::<EkInstrumentMarginRate>()
            );
            assert_eq!(
                ek_pod_sizeof_commission_rate() as usize,
                size_of::<EkInstrumentCommissionRate>()
            );
            assert_eq!(
                ek_pod_sizeof_instrument_status() as usize,
                size_of::<EkInstrumentStatus>()
            );
            assert_eq!(
                ek_pod_sizeof_qry_margin_rate() as usize,
                size_of::<EkQryInstrumentMarginRate>()
            );
            assert_eq!(
                ek_pod_sizeof_qry_commission_rate() as usize,
                size_of::<EkQryInstrumentCommissionRate>()
            );
        }
    }

    /* ---------------- (b) 8 个读方向自检 ---------------- */

    #[test]
    fn selftest_error_follows_wire_order() {
        let mut out = zeroed::<EkErrorField>();
        let mut sc = scratch();
        // SAFETY: out 是有效 POD,scratch 足够大;契约见 ek_ctp_pod.h。
        unsafe { ek_pod_selftest_error(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.error_id, k.i32());
        assert_eq!(w.error_msg, k.s());
    }

    #[test]
    fn request_path_fields_are_gbk_encoded() {
        // 0.12.0 `D-NATIVE-ENC-IN` 修正的回归钉。
        //
        // 背景:`copy_field` 曾用注释里一句未经证实的前提("请求里的 id/密码都是
        // ASCII")跳过 UTF-8→GBK 转换。中文密码于是以 UTF-8 字节进入 GBK 字段,
        // 柜台回"用户名或密码错",而 eLog 里的密码看起来完全正确 —— 这是最难
        // 排查的一类故障。
        let mut buf = [0 as c_char; 64];
        // SAFETY: 缓冲足够大(shim 侧只会写入 ≤ 40 字节 + NUL)。
        unsafe { ek_shim_selftest_copy_field(buf.as_mut_ptr(), buf.len()) };
        let bytes: Vec<u8> = buf
            .iter()
            .take_while(|c| **c != 0)
            .map(|c| *c as u8)
            .collect();
        assert_eq!(
            bytes,
            vec![0xC3, 0xDC, 0xC2, 0xEB],
            "「密码」必须按 GBK 送出去(C3DC C2EB)"
        );
        assert_ne!(
            bytes,
            b"\xE5\xAF\x86\xE7\xA0\x81".to_vec(),
            "原样返回 UTF-8 字节 = 请求路径漏了编码转换"
        );
    }

    #[test]
    fn overlong_request_field_truncates_on_character_boundary() {
        // 0.12.0 `D-LEN-GATE` 的回归钉:超长必须截断,但**不许留半个汉字**。
        //
        // 半个双字节字符送到柜台会被当成乱码,而乱码在登录流程里的表现是
        // 「密码错」—— 用户会一遍遍重输同一个密码,日志里那个密码还是对的。
        let before = crate::native::common::truncations();

        let mut buf = [0 as c_char; 64];
        // SAFETY: 缓冲足够(shim 侧只写 ≤ 40 字节 + NUL)。
        unsafe { ek_shim_selftest_copy_field_truncated(buf.as_mut_ptr(), buf.len()) };
        let bytes: Vec<u8> = buf
            .iter()
            .take_while(|c| **c != 0)
            .map(|c| *c as u8)
            .collect();

        assert_eq!(
            bytes.len(),
            40,
            "`char[41]` 只能装 40 字节,got {}",
            bytes.len()
        );
        // GBK「密」= C3 DC;按两字节步进必须恰好走完,末字节落在低位(>= 0x80 是
        // 首字节,< 0x80 是第二字节)。留半个汉字时这里会看到奇数长度的尾落单。
        let mut i = 0;
        while i < bytes.len() {
            assert!(bytes[i] >= 0x80, "第 {i} 字节应是 GBK 首字节");
            assert!(i + 1 < bytes.len(), "尾部留下半个汉字(位置 {i})");
            i += 2;
        }
        for chunk in bytes.chunks(2) {
            assert_eq!(chunk, [0xC3, 0xDC], "截断后每个汉字都应完整(C3 DC)");
        }

        let after = crate::native::common::truncations();
        assert!(
            after > before,
            "截断必须记账:计数 {before} → {after} 没变,说明 note_truncation 没走到"
        );
    }

    #[test]
    fn selftest_depth_follows_wire_order() {
        let mut out = zeroed::<EkDepthMarketData>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_depth(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.last_price, k.f64());
        assert_eq!(w.volume, k.f64());
        assert_eq!(w.turnover, k.f64());
        assert_eq!(w.open_interest, k.f64());
        assert_eq!(w.upper_limit_price, k.f64());
        assert_eq!(w.lower_limit_price, k.f64());
        assert_eq!(w.open_price, k.f64());
        assert_eq!(w.highest_price, k.f64());
        assert_eq!(w.lowest_price, k.f64());
        assert_eq!(w.pre_close_price, k.f64());
        assert_eq!(w.bid_price1, k.f64());
        assert_eq!(w.bid_price2, k.f64());
        assert_eq!(w.bid_price3, k.f64());
        assert_eq!(w.bid_price4, k.f64());
        assert_eq!(w.bid_price5, k.f64());
        assert_eq!(w.ask_price1, k.f64());
        assert_eq!(w.ask_price2, k.f64());
        assert_eq!(w.ask_price3, k.f64());
        assert_eq!(w.ask_price4, k.f64());
        assert_eq!(w.ask_price5, k.f64());
        assert_eq!(w.bid_volume1, k.f64());
        assert_eq!(w.bid_volume2, k.f64());
        assert_eq!(w.bid_volume3, k.f64());
        assert_eq!(w.bid_volume4, k.f64());
        assert_eq!(w.bid_volume5, k.f64());
        assert_eq!(w.ask_volume1, k.f64());
        assert_eq!(w.ask_volume2, k.f64());
        assert_eq!(w.ask_volume3, k.f64());
        assert_eq!(w.ask_volume4, k.f64());
        assert_eq!(w.ask_volume5, k.f64());
        assert_eq!(w.update_time, k.s());
        assert_eq!(w.update_millisec, k.i64());
        assert_eq!(w.trading_day, k.s());
        assert_eq!(w.action_day, k.s());
        // 0.12.0:交易所码镜像(k=36;放在最后断言,不打乱既有 k 编号)
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(k.next(), 37, "36 个字段,计数器应停在 36 之后");
    }

    #[test]
    fn selftest_instrument_follows_wire_order() {
        let mut out = zeroed::<EkInstrumentField>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_instrument(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(w.instrument_name, k.s());
        assert_eq!(w.product_class, k.ch());
        assert_eq!(w.volume_multiple, k.f64());
        assert_eq!(w.price_tick, k.f64());
        assert_eq!(w.max_limit_order_volume, k.f64());
        assert_eq!(w.min_limit_order_volume, k.f64());
        assert_eq!(w.max_market_order_volume, k.f64());
        assert_eq!(w.min_market_order_volume, k.f64());
        assert_eq!(w.delivery_year, k.i64());
        assert_eq!(w.delivery_month, k.i64());
        assert_eq!(w.product_id, k.s());
        assert_eq!(w.is_trading, k.i64());
        assert_eq!(k.next(), 15, "14 个字段");
    }

    #[test]
    fn selftest_order_follows_wire_order() {
        let mut out = zeroed::<EkOrderField>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_order(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.order_ref, k.s());
        assert_eq!(w.front_id, k.i64());
        assert_eq!(w.session_id, k.i64());
        assert_eq!(w.order_sys_id, k.s());
        assert_eq!(w.direction, k.ch());
        assert_eq!(w.comb_offset_flag, k.s());
        assert_eq!(w.order_price_type, k.ch());
        assert_eq!(w.time_condition, k.ch());
        assert_eq!(w.volume_condition, k.ch());
        assert_eq!(w.limit_price, k.f64());
        assert_eq!(w.volume_total_original, k.f64());
        assert_eq!(w.volume_total, k.f64());
        assert_eq!(w.volume_traded, k.f64());
        assert_eq!(w.order_status, k.ch());
        assert_eq!(w.insert_date, k.s());
        assert_eq!(w.insert_time, k.s());
        assert_eq!(k.next(), 18, "17 个字段");
    }

    #[test]
    fn selftest_trade_follows_wire_order() {
        let mut out = zeroed::<EkTradeField>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_trade(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.order_sys_id, k.s());
        assert_eq!(w.trade_id, k.s());
        assert_eq!(w.direction, k.ch());
        assert_eq!(w.offset_flag, k.ch());
        assert_eq!(w.price, k.f64());
        assert_eq!(w.volume, k.f64());
        assert_eq!(w.trade_date, k.s());
        assert_eq!(w.trade_time, k.s());
        assert_eq!(k.next(), 10, "9 个字段");
    }

    #[test]
    fn selftest_position_follows_wire_order() {
        let mut out = zeroed::<EkInvestorPositionField>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_position(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.posi_direction, k.ch());
        assert_eq!(w.yd_position, k.f64());
        assert_eq!(w.position, k.f64());
        assert_eq!(w.today_position, k.f64());
        assert_eq!(w.position_cost, k.f64());
        assert_eq!(w.position_profit, k.f64());
        assert_eq!(w.short_frozen, k.f64());
        assert_eq!(w.long_frozen, k.f64());
        assert_eq!(k.next(), 10, "9 个字段");
    }

    #[test]
    fn selftest_account_follows_wire_order() {
        let mut out = zeroed::<EkTradingAccountField>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_account(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.account_id, k.s());
        assert_eq!(w.balance, k.f64());
        assert_eq!(w.frozen_margin, k.f64());
        assert_eq!(w.frozen_cash, k.f64());
        assert_eq!(w.frozen_commission, k.f64());
        assert_eq!(w.available, k.f64());
        assert_eq!(k.next(), 7, "6 个字段");
    }

    #[test]
    fn selftest_input_order_follows_wire_order() {
        let mut out = zeroed::<EkInputOrder>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_input_order(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(w.limit_price, k.f64());
        assert_eq!(w.volume_total_original, k.i64());
        assert_eq!(w.order_price_type, k.ch());
        assert_eq!(w.direction, k.ch());
        assert_eq!(w.comb_offset_flag, k.s());
        assert_eq!(w.order_ref, k.s());
        assert_eq!(w.investor_id, k.s());
        assert_eq!(w.user_id, k.s());
        assert_eq!(w.broker_id, k.s());
        assert_eq!(w.comb_hedge_flag, k.s());
        assert_eq!(w.contingent_condition, k.ch());
        assert_eq!(w.force_close_reason, k.ch());
        assert_eq!(w.is_auto_suspend, k.i32());
        assert_eq!(w.time_condition, k.ch());
        assert_eq!(w.volume_condition, k.ch());
        assert_eq!(w.min_volume, k.i64());
        assert_eq!(k.next(), 19, "18 个字段");
    }

    /* ---------------- (c) 两个 roundtrip(自检之外的另一组值)---------------- */

    #[test]
    fn roundtrip_input_order_preserves_every_field() {
        let order = InputOrder {
            instrument_id: "rb2601".to_string(),
            exchange_id: "SHFE".to_string(),
            limit_price: 3456.5,
            volume_total_original: 7,
            order_price_type: "2".to_string(),
            direction: "0".to_string(),
            comb_offset_flag: "1".to_string(),
            order_ref: "90001".to_string(),
            investor_id: "investor-1".to_string(),
            user_id: "user-1".to_string(),
            broker_id: "broker-1".to_string(),
            comb_hedge_flag: "1".to_string(),
            contingent_condition: "1".to_string(),
            force_close_reason: "0".to_string(),
            is_auto_suspend: 0,
            time_condition: "3".to_string(),
            volume_condition: "1".to_string(),
            min_volume: 1,
        };
        let (pod, keep) = order.to_pod_cstr();
        let mut out = zeroed::<EkInputOrder>();
        let mut sc = scratch();
        // SAFETY: pod 的字符串由 keep 持有(仍存活);out/scratch 有效。
        unsafe {
            ek_pod_selftest_io_roundtrip_input_order(&pod, &mut out, scratch_ptr(&mut sc), sc.len())
        };
        let back = out.to_wire();
        assert_eq!(back, order, "POD -> CTP -> POD 必须逐字段还原");
        drop(keep);
    }

    #[test]
    fn roundtrip_input_order_action_preserves_every_field() {
        let action = InputOrderAction {
            instrument_id: "ag2612".to_string(),
            exchange_id: "SHFE".to_string(),
            order_ref: "90002".to_string(),
            front_id: 1234,
            session_id: 5678,
            action_flag: "0".to_string(),
            broker_id: "broker-2".to_string(),
            investor_id: "investor-2".to_string(),
        };
        let (pod, keep) = action.to_pod_cstr();
        let mut out = zeroed::<EkInputOrderAction>();
        let mut sc = scratch();
        // SAFETY: pod 的字符串由 keep 持有(仍存活);out/scratch 有效。
        unsafe {
            ek_pod_selftest_io_roundtrip_input_order_action(
                &pod,
                &mut out,
                scratch_ptr(&mut sc),
                sc.len(),
            )
        };
        let back = out.to_wire();
        assert_eq!(back, action, "POD -> CTP -> POD 必须逐字段还原");
        drop(keep);
    }

    /// 写方向单向校验(roundtrip 之外的**独立**面):期望结构按 CTP 字段名逐个
    /// 构造,转换内任何"拿错源字段"的错位都会在比对处显形,而非往返抵消。
    /// 各字段值互不重复,换乘也比对得出来。
    #[test]
    fn input_order_action_converter_fields_match_names() {
        let action = InputOrderAction {
            instrument_id: "vf0001".to_string(),
            exchange_id: "vf0002".to_string(),
            order_ref: "vf0003".to_string(),
            front_id: 910,
            session_id: 920,
            action_flag: "z".to_string(),
            broker_id: "vf0005".to_string(),
            investor_id: "vf0006".to_string(),
        };
        let (pod, keep) = action.to_pod_cstr();
        // SAFETY: pod 的字符串由 keep 持有(仍存活);verify 只读。
        let rc = unsafe { ek_ctp_verify_input_order_action(&pod) };
        drop(keep);
        assert_eq!(rc, 0, "写方向转换存在错位字段(首个错位序号={rc})");
    }

    /* ---------------- 附加接口面:三件(数据) + 两输入(写向) ---------------- */

    #[test]
    fn selftest_margin_rate_follows_wire_order() {
        let mut out = zeroed::<EkInstrumentMarginRate>();
        let mut sc = scratch();
        // SAFETY: out 是有效 POD,scratch 足够大。
        unsafe { ek_pod_selftest_margin_rate(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.investor_range, k.ch());
        assert_eq!(w.broker_id, k.s());
        assert_eq!(w.investor_id, k.s());
        assert_eq!(w.hedge_flag, k.ch());
        assert_eq!(w.long_margin_ratio_by_money, k.f64());
        assert_eq!(w.long_margin_ratio_by_volume, k.f64());
        assert_eq!(w.short_margin_ratio_by_money, k.f64());
        assert_eq!(w.short_margin_ratio_by_volume, k.f64());
        assert_eq!(w.is_relative, k.i32());
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(w.invest_unit_id, k.s());
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(k.next(), 13, "12 个字段");
    }

    #[test]
    fn selftest_commission_rate_follows_wire_order() {
        let mut out = zeroed::<EkInstrumentCommissionRate>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_commission_rate(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.investor_range, k.ch());
        assert_eq!(w.broker_id, k.s());
        assert_eq!(w.investor_id, k.s());
        assert_eq!(w.open_ratio_by_money, k.f64());
        assert_eq!(w.open_ratio_by_volume, k.f64());
        assert_eq!(w.close_ratio_by_money, k.f64());
        assert_eq!(w.close_ratio_by_volume, k.f64());
        assert_eq!(w.close_today_ratio_by_money, k.f64());
        assert_eq!(w.close_today_ratio_by_volume, k.f64());
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(w.biz_type, k.ch());
        assert_eq!(w.invest_unit_id, k.s());
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(k.next(), 14, "13 个字段");
    }

    #[test]
    fn selftest_instrument_status_follows_wire_order() {
        let mut out = zeroed::<EkInstrumentStatus>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe { ek_pod_selftest_instrument_status(&mut out, scratch_ptr(&mut sc), sc.len()) };
        let w = out.to_wire();
        let mut k = K::new();
        assert_eq!(w.exchange_id, k.s());
        assert_eq!(w.settlement_group_id, k.s());
        assert_eq!(w.instrument_status, k.ch());
        assert_eq!(w.trading_segment_sn, k.i32());
        assert_eq!(w.enter_time, k.s());
        assert_eq!(w.enter_reason, k.ch());
        assert_eq!(w.exchange_inst_id, k.s());
        assert_eq!(w.instrument_id, k.s());
        assert_eq!(k.next(), 9, "8 个字段");
    }

    /// 两个查询输入 POD 的写方向独立校验(按名重建期望,逐字段比对)。
    /// 特别抓两处易错:①保证金率查询的 hedge_flag 位置;②手续费率查询**没有**
    /// hedge 字段——若在 C++ 侧照抄保证金率版本,struct 编译期就过不了,运行期
    /// 错位则被独立比对抓出。
    #[test]
    fn qry_margin_rate_converter_fields_match_names() {
        let query = QryInstrumentMarginRate {
            broker_id: "wg0001".to_string(),
            investor_id: "wg0002".to_string(),
            hedge_flag: "w".to_string(),
            exchange_id: "wg0003".to_string(),
            invest_unit_id: "wg0004".to_string(),
            instrument_id: "wg0005".to_string(),
        };
        let (pod, keep) = query.to_pod_cstr();
        // SAFETY: pod 的字符串由 keep 持有(仍存活);verify 只读。
        let rc = unsafe { ek_ctp_verify_qry_margin_rate(&pod) };
        drop(keep);
        assert_eq!(rc, 0, "保证金率查询写方向存在错位字段(首个错位序号={rc})");
    }

    #[test]
    fn qry_commission_rate_converter_fields_match_names() {
        let query = QryInstrumentCommissionRate {
            broker_id: "wk0001".to_string(),
            investor_id: "wk0002".to_string(),
            exchange_id: "wk0003".to_string(),
            invest_unit_id: "wk0004".to_string(),
            instrument_id: "wk0005".to_string(),
        };
        let (pod, keep) = query.to_pod_cstr();
        // SAFETY: 同上。
        let rc = unsafe { ek_ctp_verify_qry_commission_rate(&pod) };
        drop(keep);
        assert_eq!(rc, 0, "手续费率查询写方向存在错位字段(首个错位序号={rc})");
    }

    /* ---------------- 编码与降级(GBK 真值面)---------------- */

    #[test]
    fn gbk_utf8_helpers_roundtrip_non_ascii() {
        // 7 个汉字:GBK 下 2 字节/字 = 14 字节(若是 UTF-8 会是 21 字节)。
        let text = "螺纹钢主力合约";
        let gbk = utf8_to_gbk(text);
        assert_eq!(gbk.len(), 14, "GBK 应是 2 字节/汉字");
        assert_eq!(gbk_to_utf8(&gbk), text, "GBK -> UTF-8 必须还原");

        // 空输入 → 空(不是 panic)。
        assert_eq!(gbk_to_utf8(&[]), "");
        assert_eq!(utf8_to_gbk(""), Vec::<u8>::new());

        // 非法 GBK:孤立引导字节 / 被截断的双字节序列 → 降级为空串,不崩。
        assert_eq!(gbk_to_utf8(&[0x81]), "");
        assert_eq!(gbk_to_utf8(&[0xB0]), "");
        // 合法 GBK 双字节仍能解码(证明上面不是"一律返回空")。
        let lead = utf8_to_gbk("螺");
        assert_eq!(lead.len(), 2);
        assert_eq!(gbk_to_utf8(&lead), "螺");
    }

    #[test]
    fn roundtrip_input_order_preserves_gbk_text() {
        // 走真实字段面:UTF-8 -> CTP char[] (GBK) -> UTF-8。
        let order = InputOrder {
            instrument_id: "螺纹钢2610".to_string(),
            exchange_id: "SHFE".to_string(),
            limit_price: 3200.0,
            volume_total_original: 3,
            order_price_type: "2".to_string(),
            direction: "0".to_string(),
            comb_offset_flag: "1".to_string(),
            order_ref: "70001".to_string(),
            investor_id: "投资者一号".to_string(),
            user_id: "用户甲".to_string(),
            broker_id: "经纪公司".to_string(),
            comb_hedge_flag: "1".to_string(),
            contingent_condition: "1".to_string(),
            force_close_reason: "0".to_string(),
            is_auto_suspend: 0,
            time_condition: "3".to_string(),
            volume_condition: "1".to_string(),
            min_volume: 1,
        };
        let (pod, keep) = order.to_pod_cstr();
        let mut out = zeroed::<EkInputOrder>();
        let mut sc = scratch();
        // SAFETY: 同上。
        unsafe {
            ek_pod_selftest_io_roundtrip_input_order(&pod, &mut out, scratch_ptr(&mut sc), sc.len())
        };
        let back = out.to_wire();
        assert_eq!(back, order, "GBK 字段往返必须无损");
        drop(keep);
    }

    #[test]
    fn exhausted_or_null_scratch_degrades_to_empty_strings() {
        // 只够放 1 个字符 + NUL:"s2" 放不下 → 该字段降级为空串,且不越界写。
        let mut out = zeroed::<EkErrorField>();
        let mut tiny = [0u8; 2];
        // SAFETY: tiny 只有 2 字节,shim 必须自己守住边界。
        unsafe { ek_pod_selftest_error(&mut out, scratch_ptr(&mut tiny), tiny.len()) };
        let w = out.to_wire();
        assert_eq!(w.error_id, 2001, "数值字段不受 scratch 影响");
        assert_eq!(w.error_msg, "");

        // 完全不给 scratch(空指针 + 0 容量):全部字符串降级为空串,不崩。
        let mut out2 = zeroed::<EkErrorField>();
        // SAFETY: 空指针 + 0 容量是本层的显式降级路径。
        unsafe { ek_pod_selftest_error(&mut out2, std::ptr::null_mut(), 0) };
        let w2 = out2.to_wire();
        assert_eq!(w2.error_id, 2001);
        assert_eq!(w2.error_msg, "");
    }
}