1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
//! Contains the [`SerializeCql`] trait and its implementations.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Display;
use std::hash::BuildHasher;
use std::net::IpAddr;
use std::sync::Arc;

use thiserror::Error;
use uuid::Uuid;

#[cfg(feature = "chrono")]
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};

#[cfg(feature = "secret")]
use secrecy::{ExposeSecret, Secret, Zeroize};

use crate::frame::response::result::{ColumnType, CqlValue};
use crate::frame::types::vint_encode;
use crate::frame::value::{
    Counter, CqlDate, CqlDecimal, CqlDuration, CqlTime, CqlTimestamp, CqlTimeuuid, CqlVarint,
    MaybeUnset, Unset, Value,
};

#[cfg(feature = "chrono")]
use crate::frame::value::ValueOverflow;

use super::writers::WrittenCellProof;
use super::{CellWriter, SerializationError};

/// A type that can be serialized and sent along with a CQL statement.
///
/// This is a low-level trait that is exposed to the specifics to the CQL
/// protocol and usually does not have to be implemented directly. See the
/// chapter on "Query Values" in the driver docs for information about how
/// this trait is supposed to be used.
pub trait SerializeCql {
    /// Serializes the value to given CQL type.
    ///
    /// The value should produce a `[value]`, according to the [CQL protocol
    /// specification](https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v4.spec),
    /// containing the serialized value. See section 6 of the document on how
    /// the contents of the `[value]` should look like.
    ///
    /// The value produced should match the type provided by `typ`. If the
    /// value cannot be serialized to that type, an error should be returned.
    ///
    /// The [`CellWriter`] provided to the method ensures that the value produced
    /// will be properly framed (i.e. incorrectly written value should not
    /// cause the rest of the request to be misinterpreted), but otherwise
    /// the implementor of the trait is responsible for producing the a value
    /// in a correct format.
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError>;
}

macro_rules! exact_type_check {
    ($typ:ident, $($cql:tt),*) => {
        match $typ {
            $(ColumnType::$cql)|* => {},
            _ => return Err(mk_typck_err::<Self>(
                $typ,
                BuiltinTypeCheckErrorKind::MismatchedType {
                    expected: &[$(ColumnType::$cql),*],
                }
            ))
        }
    };
}

macro_rules! impl_serialize_via_writer {
    (|$me:ident, $writer:ident| $e:expr) => {
        impl_serialize_via_writer!(|$me, _typ, $writer| $e);
    };
    (|$me:ident, $typ:ident, $writer:ident| $e:expr) => {
        fn serialize<'b>(
            &self,
            typ: &ColumnType,
            writer: CellWriter<'b>,
        ) -> Result<WrittenCellProof<'b>, SerializationError> {
            let $writer = writer;
            let $typ = typ;
            let $me = self;
            let proof = $e;
            Ok(proof)
        }
    };
}

impl SerializeCql for i8 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, TinyInt);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for i16 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, SmallInt);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for i32 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Int);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for i64 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, BigInt);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for CqlDecimal {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Decimal);
        let mut builder = writer.into_value_builder();
        let (bytes, scale) = me.as_signed_be_bytes_slice_and_exponent();
        builder.append_bytes(&scale.to_be_bytes());
        builder.append_bytes(bytes);
        builder
            .finish()
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
#[cfg(feature = "bigdecimal-04")]
impl SerializeCql for bigdecimal_04::BigDecimal {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Decimal);
        let mut builder = writer.into_value_builder();
        let (value, scale) = me.as_bigint_and_exponent();
        let scale: i32 = scale
            .try_into()
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::ValueOverflow))?;
        builder.append_bytes(&scale.to_be_bytes());
        builder.append_bytes(&value.to_signed_bytes_be());
        builder
            .finish()
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl SerializeCql for CqlDate {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Date);
        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for CqlTimestamp {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Timestamp);
        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for CqlTime {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Time);
        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
    });
}
#[cfg(feature = "chrono")]
impl SerializeCql for NaiveDate {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Date);
        <CqlDate as SerializeCql>::serialize(&(*me).into(), typ, writer)?
    });
}
#[cfg(feature = "chrono")]
impl SerializeCql for DateTime<Utc> {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Timestamp);
        <CqlTimestamp as SerializeCql>::serialize(&(*me).into(), typ, writer)?
    });
}
#[cfg(feature = "chrono")]
impl SerializeCql for NaiveTime {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Time);
        let cql_time = CqlTime::try_from(*me).map_err(|_: ValueOverflow| {
            mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::ValueOverflow)
        })?;
        <CqlTime as SerializeCql>::serialize(&cql_time, typ, writer)?
    });
}
#[cfg(feature = "time")]
impl SerializeCql for time::Date {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Date);
        <CqlDate as SerializeCql>::serialize(&(*me).into(), typ, writer)?
    });
}
#[cfg(feature = "time")]
impl SerializeCql for time::OffsetDateTime {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Timestamp);
        <CqlTimestamp as SerializeCql>::serialize(&(*me).into(), typ, writer)?
    });
}
#[cfg(feature = "time")]
impl SerializeCql for time::Time {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Time);
        <CqlTime as SerializeCql>::serialize(&(*me).into(), typ, writer)?
    });
}
#[cfg(feature = "secret")]
impl<V: SerializeCql + Zeroize> SerializeCql for Secret<V> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        V::serialize(self.expose_secret(), typ, writer)
    }
}
impl SerializeCql for bool {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Boolean);
        writer.set_value(&[*me as u8]).unwrap()
    });
}
impl SerializeCql for f32 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Float);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for f64 {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Double);
        writer.set_value(me.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for Uuid {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Uuid);
        writer.set_value(me.as_bytes().as_ref()).unwrap()
    });
}
impl SerializeCql for CqlTimeuuid {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Timeuuid);
        writer.set_value(me.as_bytes().as_ref()).unwrap()
    });
}
impl SerializeCql for CqlVarint {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Varint);
        writer
            .set_value(me.as_signed_bytes_be_slice())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
#[cfg(feature = "num-bigint-03")]
impl SerializeCql for num_bigint_03::BigInt {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Varint);
        // TODO: The allocation here can be avoided and we can reimplement
        // `to_signed_bytes_be` by using `to_u64_digits` and a bit of custom
        // logic. Need better tests in order to do this.
        writer
            .set_value(me.to_signed_bytes_be().as_slice())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
#[cfg(feature = "num-bigint-04")]
impl SerializeCql for num_bigint_04::BigInt {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Varint);
        // TODO: See above comment for num-bigint-03.
        writer
            .set_value(me.to_signed_bytes_be().as_slice())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl SerializeCql for &str {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Ascii, Text);
        writer
            .set_value(me.as_bytes())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl SerializeCql for Vec<u8> {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Blob);
        writer
            .set_value(me.as_ref())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl SerializeCql for &[u8] {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Blob);
        writer
            .set_value(me)
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl<const N: usize> SerializeCql for [u8; N] {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Blob);
        writer
            .set_value(me.as_ref())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl SerializeCql for IpAddr {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Inet);
        match me {
            IpAddr::V4(ip) => writer.set_value(&ip.octets()).unwrap(),
            IpAddr::V6(ip) => writer.set_value(&ip.octets()).unwrap(),
        }
    });
}
impl SerializeCql for String {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Ascii, Text);
        writer
            .set_value(me.as_bytes())
            .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))?
    });
}
impl<T: SerializeCql> SerializeCql for Option<T> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        match self {
            Some(v) => v.serialize(typ, writer),
            None => Ok(writer.set_null()),
        }
    }
}
impl SerializeCql for Unset {
    impl_serialize_via_writer!(|_me, writer| writer.set_unset());
}
impl SerializeCql for Counter {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Counter);
        writer.set_value(me.0.to_be_bytes().as_slice()).unwrap()
    });
}
impl SerializeCql for CqlDuration {
    impl_serialize_via_writer!(|me, typ, writer| {
        exact_type_check!(typ, Duration);
        // TODO: adjust vint_encode to use CellValueBuilder or something like that
        let mut buf = Vec::with_capacity(27); // worst case size is 27
        vint_encode(me.months as i64, &mut buf);
        vint_encode(me.days as i64, &mut buf);
        vint_encode(me.nanoseconds, &mut buf);
        writer.set_value(buf.as_slice()).unwrap()
    });
}
impl<V: SerializeCql> SerializeCql for MaybeUnset<V> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        match self {
            MaybeUnset::Set(v) => v.serialize(typ, writer),
            MaybeUnset::Unset => Ok(writer.set_unset()),
        }
    }
}
impl<T: SerializeCql + ?Sized> SerializeCql for &T {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        T::serialize(*self, typ, writer)
    }
}
impl<T: SerializeCql + ?Sized> SerializeCql for Box<T> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        T::serialize(&**self, typ, writer)
    }
}
impl<V: SerializeCql, S: BuildHasher + Default> SerializeCql for HashSet<V, S> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_sequence(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl<K: SerializeCql, V: SerializeCql, S: BuildHasher> SerializeCql for HashMap<K, V, S> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_mapping(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl<V: SerializeCql> SerializeCql for BTreeSet<V> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_sequence(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl<K: SerializeCql, V: SerializeCql> SerializeCql for BTreeMap<K, V> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_mapping(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl<T: SerializeCql> SerializeCql for Vec<T> {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_sequence(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl<'a, T: SerializeCql + 'a> SerializeCql for &'a [T] {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_sequence(
            std::any::type_name::<Self>(),
            self.len(),
            self.iter(),
            typ,
            writer,
        )
    }
}
impl SerializeCql for CqlValue {
    fn serialize<'b>(
        &self,
        typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_cql_value(self, typ, writer).map_err(fix_cql_value_name_in_err)
    }
}

fn serialize_cql_value<'b>(
    value: &CqlValue,
    typ: &ColumnType,
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    if let ColumnType::Custom(_) = typ {
        return Err(mk_typck_err::<CqlValue>(
            typ,
            BuiltinTypeCheckErrorKind::CustomTypeUnsupported,
        ));
    }
    match value {
        CqlValue::Ascii(a) => <_ as SerializeCql>::serialize(&a, typ, writer),
        CqlValue::Boolean(b) => <_ as SerializeCql>::serialize(&b, typ, writer),
        CqlValue::Blob(b) => <_ as SerializeCql>::serialize(&b, typ, writer),
        CqlValue::Counter(c) => <_ as SerializeCql>::serialize(&c, typ, writer),
        CqlValue::Decimal(d) => <_ as SerializeCql>::serialize(&d, typ, writer),
        CqlValue::Date(d) => <_ as SerializeCql>::serialize(&d, typ, writer),
        CqlValue::Double(d) => <_ as SerializeCql>::serialize(&d, typ, writer),
        CqlValue::Duration(d) => <_ as SerializeCql>::serialize(&d, typ, writer),
        CqlValue::Empty => {
            if !typ.supports_special_empty_value() {
                return Err(mk_typck_err::<CqlValue>(
                    typ,
                    BuiltinTypeCheckErrorKind::NotEmptyable,
                ));
            }
            Ok(writer.set_value(&[]).unwrap())
        }
        CqlValue::Float(f) => <_ as SerializeCql>::serialize(&f, typ, writer),
        CqlValue::Int(i) => <_ as SerializeCql>::serialize(&i, typ, writer),
        CqlValue::BigInt(b) => <_ as SerializeCql>::serialize(&b, typ, writer),
        CqlValue::Text(t) => <_ as SerializeCql>::serialize(&t, typ, writer),
        CqlValue::Timestamp(t) => <_ as SerializeCql>::serialize(&t, typ, writer),
        CqlValue::Inet(i) => <_ as SerializeCql>::serialize(&i, typ, writer),
        CqlValue::List(l) => <_ as SerializeCql>::serialize(&l, typ, writer),
        CqlValue::Map(m) => serialize_mapping(
            std::any::type_name::<CqlValue>(),
            m.len(),
            m.iter().map(|p| (&p.0, &p.1)),
            typ,
            writer,
        ),
        CqlValue::Set(s) => <_ as SerializeCql>::serialize(&s, typ, writer),
        CqlValue::UserDefinedType {
            keyspace,
            type_name,
            fields,
        } => serialize_udt(typ, keyspace, type_name, fields, writer),
        CqlValue::SmallInt(s) => <_ as SerializeCql>::serialize(&s, typ, writer),
        CqlValue::TinyInt(t) => <_ as SerializeCql>::serialize(&t, typ, writer),
        CqlValue::Time(t) => <_ as SerializeCql>::serialize(&t, typ, writer),
        CqlValue::Timeuuid(t) => <_ as SerializeCql>::serialize(&t, typ, writer),
        CqlValue::Tuple(t) => {
            // We allow serializing tuples that have less fields
            // than the database tuple, but not the other way around.
            let fields = match typ {
                ColumnType::Tuple(fields) => {
                    if fields.len() < t.len() {
                        return Err(mk_typck_err::<CqlValue>(
                            typ,
                            TupleTypeCheckErrorKind::WrongElementCount {
                                actual: t.len(),
                                asked_for: fields.len(),
                            },
                        ));
                    }
                    fields
                }
                _ => {
                    return Err(mk_typck_err::<CqlValue>(
                        typ,
                        TupleTypeCheckErrorKind::NotTuple,
                    ))
                }
            };
            serialize_tuple_like(typ, fields.iter(), t.iter(), writer)
        }
        CqlValue::Uuid(u) => <_ as SerializeCql>::serialize(&u, typ, writer),
        CqlValue::Varint(v) => <_ as SerializeCql>::serialize(&v, typ, writer),
    }
}

fn fix_cql_value_name_in_err(mut err: SerializationError) -> SerializationError {
    // The purpose of this function is to change the `rust_name` field
    // in the error to CqlValue. Most of the time, the `err` given to the
    // function here will be the sole owner of the data, so theoretically
    // we could fix this in place.

    let rust_name = std::any::type_name::<CqlValue>();

    match Arc::get_mut(&mut err.0) {
        Some(err_mut) => {
            if let Some(err) = err_mut.downcast_mut::<BuiltinTypeCheckError>() {
                err.rust_name = rust_name;
            } else if let Some(err) = err_mut.downcast_mut::<BuiltinSerializationError>() {
                err.rust_name = rust_name;
            }
        }
        None => {
            // The `None` case shouldn't happen consisdering how we are using
            // the function in the code now, but let's provide it here anyway
            // for correctness.
            if let Some(err) = err.0.downcast_ref::<BuiltinTypeCheckError>() {
                if err.rust_name != rust_name {
                    return SerializationError::new(BuiltinTypeCheckError {
                        rust_name,
                        ..err.clone()
                    });
                }
            }
            if let Some(err) = err.0.downcast_ref::<BuiltinSerializationError>() {
                if err.rust_name != rust_name {
                    return SerializationError::new(BuiltinSerializationError {
                        rust_name,
                        ..err.clone()
                    });
                }
            }
        }
    };

    err
}

fn serialize_udt<'b>(
    typ: &ColumnType,
    keyspace: &str,
    type_name: &str,
    values: &[(String, Option<CqlValue>)],
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    let (dst_type_name, dst_keyspace, field_types) = match typ {
        ColumnType::UserDefinedType {
            type_name,
            keyspace,
            field_types,
        } => (type_name, keyspace, field_types),
        _ => return Err(mk_typck_err::<CqlValue>(typ, UdtTypeCheckErrorKind::NotUdt)),
    };

    if keyspace != dst_keyspace || type_name != dst_type_name {
        return Err(mk_typck_err::<CqlValue>(
            typ,
            UdtTypeCheckErrorKind::NameMismatch {
                keyspace: dst_keyspace.clone(),
                type_name: dst_type_name.clone(),
            },
        ));
    }

    // Allow columns present in the CQL type which are not present in CqlValue,
    // but not the other way around
    let mut indexed_fields: HashMap<_, _> = values.iter().map(|(k, v)| (k.as_str(), v)).collect();

    let mut builder = writer.into_value_builder();
    for (fname, ftyp) in field_types {
        // Take a value from the original list.
        // If a field is missing, write null instead.
        let fvalue = indexed_fields
            .remove(fname.as_str())
            .and_then(|x| x.as_ref());

        let writer = builder.make_sub_writer();
        match fvalue {
            None => writer.set_null(),
            Some(v) => serialize_cql_value(v, ftyp, writer).map_err(|err| {
                let err = fix_cql_value_name_in_err(err);
                mk_ser_err::<CqlValue>(
                    typ,
                    UdtSerializationErrorKind::FieldSerializationFailed {
                        field_name: fname.clone(),
                        err,
                    },
                )
            })?,
        };
    }

    // If there are some leftover fields, it's an error.
    if !indexed_fields.is_empty() {
        // In order to have deterministic errors, return an error about
        // the lexicographically smallest field.
        let fname = indexed_fields.keys().min().unwrap();
        return Err(mk_typck_err::<CqlValue>(
            typ,
            UdtTypeCheckErrorKind::NoSuchFieldInUdt {
                field_name: fname.to_string(),
            },
        ));
    }

    builder
        .finish()
        .map_err(|_| mk_ser_err::<CqlValue>(typ, BuiltinSerializationErrorKind::SizeOverflow))
}

fn serialize_tuple_like<'t, 'b>(
    typ: &ColumnType,
    field_types: impl Iterator<Item = &'t ColumnType>,
    field_values: impl Iterator<Item = &'t Option<CqlValue>>,
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    let mut builder = writer.into_value_builder();

    for (index, (el, el_typ)) in field_values.zip(field_types).enumerate() {
        let sub = builder.make_sub_writer();
        match el {
            None => sub.set_null(),
            Some(el) => serialize_cql_value(el, el_typ, sub).map_err(|err| {
                let err = fix_cql_value_name_in_err(err);
                mk_ser_err::<CqlValue>(
                    typ,
                    TupleSerializationErrorKind::ElementSerializationFailed { index, err },
                )
            })?,
        };
    }

    builder
        .finish()
        .map_err(|_| mk_ser_err::<CqlValue>(typ, BuiltinSerializationErrorKind::SizeOverflow))
}

macro_rules! impl_tuple {
    (
        $($typs:ident),*;
        $($fidents:ident),*;
        $($tidents:ident),*;
        $length:expr
    ) => {
        impl<$($typs: SerializeCql),*> SerializeCql for ($($typs,)*) {
            fn serialize<'b>(
                &self,
                typ: &ColumnType,
                writer: CellWriter<'b>,
            ) -> Result<WrittenCellProof<'b>, SerializationError> {
                let ($($tidents,)*) = match typ {
                    ColumnType::Tuple(typs) => match typs.as_slice() {
                        [$($tidents),*] => ($($tidents,)*),
                        _ => return Err(mk_typck_err::<Self>(
                            typ,
                            TupleTypeCheckErrorKind::WrongElementCount {
                                actual: $length,
                                asked_for: typs.len(),
                            }
                        ))
                    }
                    _ => return Err(mk_typck_err::<Self>(
                        typ,
                        TupleTypeCheckErrorKind::NotTuple,
                    ))
                };
                let ($($fidents,)*) = self;
                let mut builder = writer.into_value_builder();
                let index = 0;
                $(
                    <$typs as SerializeCql>::serialize($fidents, $tidents, builder.make_sub_writer())
                        .map_err(|err| mk_ser_err::<Self>(
                            typ,
                            TupleSerializationErrorKind::ElementSerializationFailed {
                                index,
                                err,
                            }
                        ))?;
                    let index = index + 1;
                )*
                let _ = index;
                builder
                    .finish()
                    .map_err(|_| mk_ser_err::<Self>(typ, BuiltinSerializationErrorKind::SizeOverflow))
            }
        }
    };
}

macro_rules! impl_tuples {
    (;;;$length:expr) => {};
    (
        $typ:ident$(, $($typs:ident),*)?;
        $fident:ident$(, $($fidents:ident),*)?;
        $tident:ident$(, $($tidents:ident),*)?;
        $length:expr
    ) => {
        impl_tuples!(
            $($($typs),*)?;
            $($($fidents),*)?;
            $($($tidents),*)?;
            $length - 1
        );
        impl_tuple!(
            $typ$(, $($typs),*)?;
            $fident$(, $($fidents),*)?;
            $tident$(, $($tidents),*)?;
            $length
        );
    };
}

impl_tuples!(
    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15;
    f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15;
    t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15;
    16
);

fn serialize_sequence<'t, 'b, T: SerializeCql + 't>(
    rust_name: &'static str,
    len: usize,
    iter: impl Iterator<Item = &'t T>,
    typ: &ColumnType,
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    let elt = match typ {
        ColumnType::List(elt) | ColumnType::Set(elt) => elt,
        _ => {
            return Err(mk_typck_err_named(
                rust_name,
                typ,
                SetOrListTypeCheckErrorKind::NotSetOrList,
            ));
        }
    };

    let mut builder = writer.into_value_builder();

    let element_count: i32 = len.try_into().map_err(|_| {
        mk_ser_err_named(
            rust_name,
            typ,
            SetOrListSerializationErrorKind::TooManyElements,
        )
    })?;
    builder.append_bytes(&element_count.to_be_bytes());

    for el in iter {
        T::serialize(el, elt, builder.make_sub_writer()).map_err(|err| {
            mk_ser_err_named(
                rust_name,
                typ,
                SetOrListSerializationErrorKind::ElementSerializationFailed(err),
            )
        })?;
    }

    builder
        .finish()
        .map_err(|_| mk_ser_err_named(rust_name, typ, BuiltinSerializationErrorKind::SizeOverflow))
}

fn serialize_mapping<'t, 'b, K: SerializeCql + 't, V: SerializeCql + 't>(
    rust_name: &'static str,
    len: usize,
    iter: impl Iterator<Item = (&'t K, &'t V)>,
    typ: &ColumnType,
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    let (ktyp, vtyp) = match typ {
        ColumnType::Map(k, v) => (k, v),
        _ => {
            return Err(mk_typck_err_named(
                rust_name,
                typ,
                MapTypeCheckErrorKind::NotMap,
            ));
        }
    };

    let mut builder = writer.into_value_builder();

    let element_count: i32 = len.try_into().map_err(|_| {
        mk_ser_err_named(rust_name, typ, MapSerializationErrorKind::TooManyElements)
    })?;
    builder.append_bytes(&element_count.to_be_bytes());

    for (k, v) in iter {
        K::serialize(k, ktyp, builder.make_sub_writer()).map_err(|err| {
            mk_ser_err_named(
                rust_name,
                typ,
                MapSerializationErrorKind::KeySerializationFailed(err),
            )
        })?;
        V::serialize(v, vtyp, builder.make_sub_writer()).map_err(|err| {
            mk_ser_err_named(
                rust_name,
                typ,
                MapSerializationErrorKind::ValueSerializationFailed(err),
            )
        })?;
    }

    builder
        .finish()
        .map_err(|_| mk_ser_err_named(rust_name, typ, BuiltinSerializationErrorKind::SizeOverflow))
}

/// Implements the [`SerializeCql`] trait for a type, provided that the type
/// already implements the legacy [`Value`](crate::frame::value::Value) trait.
///
/// # Note
///
/// The translation from one trait to another encounters a performance penalty
/// and does not utilize the stronger guarantees of `SerializeCql`. Before
/// resorting to this macro, you should consider other options instead:
///
/// - If the impl was generated using the `Value` procedural macro, you should
///   switch to the `SerializeCql` procedural macro. *The new macro behaves
///   differently by default, so please read its documentation first!*
/// - If the impl was written by hand, it is still preferable to rewrite it
///   manually. You have an opportunity to make your serialization logic
///   type-safe and potentially improve performance.
///
/// Basically, you should consider using the macro if you have a hand-written
/// impl and the moment it is not easy/not desirable to rewrite it.
///
/// # Example
///
/// ```rust
/// # use scylla_cql::frame::value::{Value, ValueTooBig};
/// # use scylla_cql::impl_serialize_cql_via_value;
/// struct NoGenerics {}
/// impl Value for NoGenerics {
///     fn serialize<'b>(&self, _buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
///         Ok(())
///     }
/// }
/// impl_serialize_cql_via_value!(NoGenerics);
///
/// // Generic types are also supported. You must specify the bounds if the
/// // struct/enum contains any.
/// struct WithGenerics<T, U: Clone>(T, U);
/// impl<T: Value, U: Clone + Value> Value for WithGenerics<T, U> {
///     fn serialize<'b>(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
///         self.0.serialize(buf)?;
///         self.1.clone().serialize(buf)?;
///         Ok(())
///     }
/// }
/// impl_serialize_cql_via_value!(WithGenerics<T, U: Clone>);
/// ```
#[macro_export]
macro_rules! impl_serialize_cql_via_value {
    ($t:ident$(<$($targ:tt $(: $tbound:tt)?),*>)?) => {
        impl $(<$($targ $(: $tbound)?),*>)? $crate::types::serialize::value::SerializeCql
        for $t$(<$($targ),*>)?
        where
            Self: $crate::frame::value::Value,
        {
            fn serialize<'b>(
                &self,
                _typ: &$crate::frame::response::result::ColumnType,
                writer: $crate::types::serialize::writers::CellWriter<'b>,
            ) -> ::std::result::Result<
                $crate::types::serialize::writers::WrittenCellProof<'b>,
                $crate::types::serialize::SerializationError,
            > {
                $crate::types::serialize::value::serialize_legacy_value(self, writer)
            }
        }
    };
}

/// Implements [`SerializeCql`] if the type wrapped over implements [`Value`].
///
/// See the [`impl_serialize_cql_via_value`] macro on information about
/// the properties of the [`SerializeCql`] implementation.
pub struct ValueAdapter<T>(pub T);

impl<T> SerializeCql for ValueAdapter<T>
where
    T: Value,
{
    #[inline]
    fn serialize<'b>(
        &self,
        _typ: &ColumnType,
        writer: CellWriter<'b>,
    ) -> Result<WrittenCellProof<'b>, SerializationError> {
        serialize_legacy_value(&self.0, writer)
    }
}

/// Serializes a value implementing [`Value`] by using the [`CellWriter`]
/// interface.
///
/// The function first serializes the value with [`Value::serialize`], then
/// parses the result and serializes it again with given `CellWriter`. It is
/// a lazy and inefficient way to implement `CellWriter` via an existing `Value`
/// impl.
///
/// Returns an error if the result of the `Value::serialize` call was not
/// a properly encoded `[value]` as defined in the CQL protocol spec.
///
/// See [`impl_serialize_cql_via_value`] which generates a boilerplate
/// [`SerializeCql`] implementation that uses this function.
pub fn serialize_legacy_value<'b, T: Value>(
    v: &T,
    writer: CellWriter<'b>,
) -> Result<WrittenCellProof<'b>, SerializationError> {
    // It's an inefficient and slightly tricky but correct implementation.
    let mut buf = Vec::new();
    <T as Value>::serialize(v, &mut buf)
        .map_err(|_| SerializationError::new(ValueToSerializeCqlAdapterError::TooBig))?;

    // Analyze the output.
    // All this dance shows how unsafe our previous interface was...
    if buf.len() < 4 {
        return Err(SerializationError(Arc::new(
            ValueToSerializeCqlAdapterError::TooShort { size: buf.len() },
        )));
    }

    let (len_bytes, contents) = buf.split_at(4);
    let len = i32::from_be_bytes(len_bytes.try_into().unwrap());
    match len {
        -2 => Ok(writer.set_unset()),
        -1 => Ok(writer.set_null()),
        len if len >= 0 => {
            if contents.len() != len as usize {
                Err(SerializationError(Arc::new(
                    ValueToSerializeCqlAdapterError::DeclaredVsActualSizeMismatch {
                        declared: len as usize,
                        actual: contents.len(),
                    },
                )))
            } else {
                Ok(writer.set_value(contents).unwrap()) // len <= i32::MAX, so unwrap will succeed
            }
        }
        _ => Err(SerializationError(Arc::new(
            ValueToSerializeCqlAdapterError::InvalidDeclaredSize { size: len },
        ))),
    }
}

/// Type checking of one of the built-in types failed.
#[derive(Debug, Error, Clone)]
#[error("Failed to type check Rust type {rust_name} against CQL type {got:?}: {kind}")]
pub struct BuiltinTypeCheckError {
    /// Name of the Rust type being serialized.
    pub rust_name: &'static str,

    /// The CQL type that the Rust type was being serialized to.
    pub got: ColumnType,

    /// Detailed information about the failure.
    pub kind: BuiltinTypeCheckErrorKind,
}

fn mk_typck_err<T>(
    got: &ColumnType,
    kind: impl Into<BuiltinTypeCheckErrorKind>,
) -> SerializationError {
    mk_typck_err_named(std::any::type_name::<T>(), got, kind)
}

fn mk_typck_err_named(
    name: &'static str,
    got: &ColumnType,
    kind: impl Into<BuiltinTypeCheckErrorKind>,
) -> SerializationError {
    SerializationError::new(BuiltinTypeCheckError {
        rust_name: name,
        got: got.clone(),
        kind: kind.into(),
    })
}

/// Serialization of one of the built-in types failed.
#[derive(Debug, Error, Clone)]
#[error("Failed to serialize Rust type {rust_name} into CQL type {got:?}: {kind}")]
pub struct BuiltinSerializationError {
    /// Name of the Rust type being serialized.
    pub rust_name: &'static str,

    /// The CQL type that the Rust type was being serialized to.
    pub got: ColumnType,

    /// Detailed information about the failure.
    pub kind: BuiltinSerializationErrorKind,
}

fn mk_ser_err<T>(
    got: &ColumnType,
    kind: impl Into<BuiltinSerializationErrorKind>,
) -> SerializationError {
    mk_ser_err_named(std::any::type_name::<T>(), got, kind)
}

fn mk_ser_err_named(
    name: &'static str,
    got: &ColumnType,
    kind: impl Into<BuiltinSerializationErrorKind>,
) -> SerializationError {
    SerializationError::new(BuiltinSerializationError {
        rust_name: name,
        got: got.clone(),
        kind: kind.into(),
    })
}

/// Describes why type checking some of the built-in types has failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BuiltinTypeCheckErrorKind {
    /// Expected one from a list of particular types.
    MismatchedType {
        /// The list of types that the Rust type can serialize as.
        expected: &'static [ColumnType],
    },

    /// Expected a type that can be empty.
    NotEmptyable,

    /// A type check failure specific to a CQL set or list.
    SetOrListError(SetOrListTypeCheckErrorKind),

    /// A type check failure specific to a CQL map.
    MapError(MapTypeCheckErrorKind),

    /// A type check failure specific to a CQL tuple.
    TupleError(TupleTypeCheckErrorKind),

    /// A type check failure specific to a CQL UDT.
    UdtError(UdtTypeCheckErrorKind),

    /// Custom CQL type - unsupported
    // TODO: Should we actually support it? Counters used to be implemented like that.
    CustomTypeUnsupported,
}

impl From<SetOrListTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
    fn from(value: SetOrListTypeCheckErrorKind) -> Self {
        BuiltinTypeCheckErrorKind::SetOrListError(value)
    }
}

impl From<MapTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
    fn from(value: MapTypeCheckErrorKind) -> Self {
        BuiltinTypeCheckErrorKind::MapError(value)
    }
}

impl From<TupleTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
    fn from(value: TupleTypeCheckErrorKind) -> Self {
        BuiltinTypeCheckErrorKind::TupleError(value)
    }
}

impl From<UdtTypeCheckErrorKind> for BuiltinTypeCheckErrorKind {
    fn from(value: UdtTypeCheckErrorKind) -> Self {
        BuiltinTypeCheckErrorKind::UdtError(value)
    }
}

impl Display for BuiltinTypeCheckErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuiltinTypeCheckErrorKind::MismatchedType { expected } => {
                write!(f, "expected one of the CQL types: {expected:?}")
            }
            BuiltinTypeCheckErrorKind::NotEmptyable => {
                write!(
                    f,
                    "the separate empty representation is not valid for this type"
                )
            }
            BuiltinTypeCheckErrorKind::SetOrListError(err) => err.fmt(f),
            BuiltinTypeCheckErrorKind::MapError(err) => err.fmt(f),
            BuiltinTypeCheckErrorKind::TupleError(err) => err.fmt(f),
            BuiltinTypeCheckErrorKind::UdtError(err) => err.fmt(f),
            BuiltinTypeCheckErrorKind::CustomTypeUnsupported => {
                write!(f, "custom CQL types are unsupported")
            }
        }
    }
}

/// Describes why serialization of some of the built-in types has failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BuiltinSerializationErrorKind {
    /// The size of the Rust value is too large to fit in the CQL serialization
    /// format (over i32::MAX bytes).
    SizeOverflow,

    /// The Rust value is out of range supported by the CQL type.
    ValueOverflow,

    /// A serialization failure specific to a CQL set or list.
    SetOrListError(SetOrListSerializationErrorKind),

    /// A serialization failure specific to a CQL map.
    MapError(MapSerializationErrorKind),

    /// A serialization failure specific to a CQL tuple.
    TupleError(TupleSerializationErrorKind),

    /// A serialization failure specific to a CQL UDT.
    UdtError(UdtSerializationErrorKind),
}

impl From<SetOrListSerializationErrorKind> for BuiltinSerializationErrorKind {
    fn from(value: SetOrListSerializationErrorKind) -> Self {
        BuiltinSerializationErrorKind::SetOrListError(value)
    }
}

impl From<MapSerializationErrorKind> for BuiltinSerializationErrorKind {
    fn from(value: MapSerializationErrorKind) -> Self {
        BuiltinSerializationErrorKind::MapError(value)
    }
}

impl From<TupleSerializationErrorKind> for BuiltinSerializationErrorKind {
    fn from(value: TupleSerializationErrorKind) -> Self {
        BuiltinSerializationErrorKind::TupleError(value)
    }
}

impl From<UdtSerializationErrorKind> for BuiltinSerializationErrorKind {
    fn from(value: UdtSerializationErrorKind) -> Self {
        BuiltinSerializationErrorKind::UdtError(value)
    }
}

impl Display for BuiltinSerializationErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuiltinSerializationErrorKind::SizeOverflow => {
                write!(
                    f,
                    "the Rust value is too big to be serialized in the CQL protocol format"
                )
            }
            BuiltinSerializationErrorKind::ValueOverflow => {
                write!(
                    f,
                    "the Rust value is out of range supported by the CQL type"
                )
            }
            BuiltinSerializationErrorKind::SetOrListError(err) => err.fmt(f),
            BuiltinSerializationErrorKind::MapError(err) => err.fmt(f),
            BuiltinSerializationErrorKind::TupleError(err) => err.fmt(f),
            BuiltinSerializationErrorKind::UdtError(err) => err.fmt(f),
        }
    }
}

/// Describes why type checking of a map type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MapTypeCheckErrorKind {
    /// The CQL type is not a map.
    NotMap,
}

impl Display for MapTypeCheckErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MapTypeCheckErrorKind::NotMap => {
                write!(
                    f,
                    "the CQL type the map was attempted to be serialized to was not map"
                )
            }
        }
    }
}

/// Describes why serialization of a map type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MapSerializationErrorKind {
    /// The many contains too many items, exceeding the protocol limit (i32::MAX).
    TooManyElements,

    /// One of the keys in the map failed to serialize.
    KeySerializationFailed(SerializationError),

    /// One of the values in the map failed to serialize.
    ValueSerializationFailed(SerializationError),
}

impl Display for MapSerializationErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MapSerializationErrorKind::TooManyElements => {
                write!(
                    f,
                    "the map contains too many elements to fit in CQL representation"
                )
            }
            MapSerializationErrorKind::KeySerializationFailed(err) => {
                write!(f, "failed to serialize one of the keys: {}", err)
            }
            MapSerializationErrorKind::ValueSerializationFailed(err) => {
                write!(f, "failed to serialize one of the values: {}", err)
            }
        }
    }
}

/// Describes why type checking of a set or list type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SetOrListTypeCheckErrorKind {
    /// The CQL type is neither a set not a list.
    NotSetOrList,
}

impl Display for SetOrListTypeCheckErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SetOrListTypeCheckErrorKind::NotSetOrList => {
                write!(
                    f,
                    "the CQL type the tuple was attempted to was neither a set or a list"
                )
            }
        }
    }
}

/// Describes why serialization of a set or list type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SetOrListSerializationErrorKind {
    /// The set/list contains too many items, exceeding the protocol limit (i32::MAX).
    TooManyElements,

    /// One of the elements of the set/list failed to serialize.
    ElementSerializationFailed(SerializationError),
}

impl Display for SetOrListSerializationErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SetOrListSerializationErrorKind::TooManyElements => {
                write!(
                    f,
                    "the collection contains too many elements to fit in CQL representation"
                )
            }
            SetOrListSerializationErrorKind::ElementSerializationFailed(err) => {
                write!(f, "failed to serialize one of the elements: {err}")
            }
        }
    }
}

/// Describes why type checking of a tuple failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum TupleTypeCheckErrorKind {
    /// The CQL type is not a tuple.
    NotTuple,

    /// The tuple has the wrong element count.
    ///
    /// Note that it is allowed to write a Rust tuple with less elements
    /// than the corresponding CQL type, but not more. The additional, unknown
    /// elements will be set to null.
    WrongElementCount {
        /// The number of elements that the Rust tuple has.
        actual: usize,

        /// The number of elements that the CQL tuple type has.
        asked_for: usize,
    },
}

impl Display for TupleTypeCheckErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TupleTypeCheckErrorKind::NotTuple => write!(
                f,
                "the CQL type the tuple was attempted to be serialized to is not a tuple"
            ),
            TupleTypeCheckErrorKind::WrongElementCount { actual, asked_for } => write!(
                f,
                "wrong tuple element count: CQL type has {asked_for}, the Rust tuple has {actual}"
            ),
        }
    }
}

/// Describes why serialize of a tuple failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum TupleSerializationErrorKind {
    /// One of the tuple elements failed to serialize.
    ElementSerializationFailed {
        /// Index of the tuple element that failed to serialize.
        index: usize,

        /// The error that caused the tuple field serialization to fail.
        err: SerializationError,
    },
}

impl Display for TupleSerializationErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TupleSerializationErrorKind::ElementSerializationFailed { index, err } => {
                write!(f, "element no. {index} failed to serialize: {err}")
            }
        }
    }
}

/// Describes why type checking of a user defined type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum UdtTypeCheckErrorKind {
    /// The CQL type is not a user defined type.
    NotUdt,

    /// The name of the UDT being serialized to does not match.
    NameMismatch {
        /// Keyspace in which the UDT was defined.
        keyspace: String,

        /// Name of the UDT.
        type_name: String,
    },

    /// The Rust data does not have a field that is required in the CQL UDT type.
    ValueMissingForUdtField {
        /// Name of field that the CQL UDT requires but is missing in the Rust struct.
        field_name: String,
    },

    /// The Rust data contains a field that is not present in the UDT.
    NoSuchFieldInUdt {
        /// Name of the Rust struct field that is missing in the UDT.
        field_name: String,
    },

    /// A different field name was expected at given position.
    FieldNameMismatch {
        /// The name of the Rust field.
        rust_field_name: String,

        /// The name of the CQL UDT field.
        db_field_name: String,
    },
}

impl Display for UdtTypeCheckErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UdtTypeCheckErrorKind::NotUdt => write!(
                f,
                "the CQL type the tuple was attempted to be type checked against is not a UDT"
            ),
            UdtTypeCheckErrorKind::NameMismatch {
                keyspace,
                type_name,
            } => write!(
                f,
                "the Rust UDT name does not match the actual CQL UDT name ({keyspace}.{type_name})"
            ),
            UdtTypeCheckErrorKind::ValueMissingForUdtField { field_name } => {
                write!(f, "the field {field_name} is missing in the Rust data but is required by the CQL UDT type")
            }
            UdtTypeCheckErrorKind::NoSuchFieldInUdt { field_name } => write!(
                f,
                "the field {field_name} that is present in the Rust data is not present in the CQL type"
            ),
            UdtTypeCheckErrorKind::FieldNameMismatch { rust_field_name, db_field_name } => write!(
                f,
                "expected field with name {db_field_name} at given position, but the Rust field name is {rust_field_name}"
            ),
        }
    }
}

/// Describes why serialization of a user defined type failed.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum UdtSerializationErrorKind {
    /// One of the fields failed to serialize.
    FieldSerializationFailed {
        /// Name of the field which failed to serialize.
        field_name: String,

        /// The error that caused the UDT field serialization to fail.
        err: SerializationError,
    },
}

impl Display for UdtSerializationErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UdtSerializationErrorKind::FieldSerializationFailed { field_name, err } => {
                write!(f, "field {field_name} failed to serialize: {err}")
            }
        }
    }
}

/// Describes a failure to translate the output of the [`Value`] legacy trait
/// into an output of the [`SerializeCql`] trait.
#[derive(Error, Debug)]
pub enum ValueToSerializeCqlAdapterError {
    /// The value is too bit to be serialized as it exceeds the maximum 2GB size limit.
    #[error("The value is too big to be serialized as it exceeds the maximum 2GB size limit")]
    TooBig,

    /// Output produced by the Value trait is less than 4 bytes in size and cannot be considered to be a proper CQL-encoded value.
    #[error("Output produced by the Value trait is too short to be considered a value: {size} < 4 minimum bytes")]
    TooShort {
        /// Size of the produced data.
        size: usize,
    },

    /// Mismatch between the value size written at the beginning and the actual size of the data appended to the Vec.
    #[error("Mismatch between the declared value size vs. actual size: {declared} != {actual}")]
    DeclaredVsActualSizeMismatch {
        /// The declared size of the output.
        declared: usize,

        /// The actual size of the output.
        actual: usize,
    },

    /// The value size written at the beginning is invalid (it is negative and less than -2).
    #[error("Invalid declared value size: {size}")]
    InvalidDeclaredSize {
        /// Declared size of the output.
        size: i32,
    },
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use crate::frame::response::result::{ColumnType, CqlValue};
    use crate::frame::value::{Counter, MaybeUnset, Unset, Value, ValueTooBig};
    use crate::types::serialize::value::{
        BuiltinSerializationError, BuiltinSerializationErrorKind, BuiltinTypeCheckError,
        BuiltinTypeCheckErrorKind, MapSerializationErrorKind, MapTypeCheckErrorKind,
        SetOrListSerializationErrorKind, SetOrListTypeCheckErrorKind, TupleSerializationErrorKind,
        TupleTypeCheckErrorKind, ValueAdapter,
    };
    use crate::types::serialize::{CellWriter, SerializationError};

    use scylla_macros::SerializeCql;

    use super::{SerializeCql, UdtSerializationErrorKind, UdtTypeCheckErrorKind};

    fn check_compat<V: Value + SerializeCql>(v: V) {
        let mut legacy_data = Vec::new();
        <V as Value>::serialize(&v, &mut legacy_data).unwrap();

        let mut new_data = Vec::new();
        let new_data_writer = CellWriter::new(&mut new_data);
        <V as SerializeCql>::serialize(&v, &ColumnType::Int, new_data_writer).unwrap();

        assert_eq!(legacy_data, new_data);
    }

    #[test]
    fn test_legacy_fallback() {
        check_compat(123i32);
        check_compat(None::<i32>);
        check_compat(MaybeUnset::Unset::<i32>);
    }

    #[test]
    fn test_dyn_serialize_cql() {
        let v: i32 = 123;
        let mut typed_data = Vec::new();
        let typed_data_writer = CellWriter::new(&mut typed_data);
        <_ as SerializeCql>::serialize(&v, &ColumnType::Int, typed_data_writer).unwrap();

        let v = &v as &dyn SerializeCql;
        let mut erased_data = Vec::new();
        let erased_data_writer = CellWriter::new(&mut erased_data);
        <_ as SerializeCql>::serialize(&v, &ColumnType::Int, erased_data_writer).unwrap();

        assert_eq!(typed_data, erased_data);
    }

    fn do_serialize<T: SerializeCql>(t: T, typ: &ColumnType) -> Vec<u8> {
        let mut ret = Vec::new();
        let writer = CellWriter::new(&mut ret);
        t.serialize(typ, writer).unwrap();
        ret
    }

    fn do_serialize_err<T: SerializeCql>(t: T, typ: &ColumnType) -> SerializationError {
        let mut ret = Vec::new();
        let writer = CellWriter::new(&mut ret);
        t.serialize(typ, writer).unwrap_err()
    }

    #[test]
    fn test_legacy_wrapper() {
        struct Foo;
        impl Value for Foo {
            fn serialize(&self, buf: &mut Vec<u8>) -> Result<(), ValueTooBig> {
                let s = "Ala ma kota";
                buf.extend_from_slice(&(s.len() as i32).to_be_bytes());
                buf.extend_from_slice(s.as_bytes());
                Ok(())
            }
        }

        let buf = do_serialize(ValueAdapter(Foo), &ColumnType::Text);
        let expected = vec![
            0, 0, 0, 11, // Length of the value
            65, 108, 97, 32, 109, 97, 32, 107, 111, 116, 97, // The string
        ];
        assert_eq!(buf, expected);
    }

    fn get_typeck_err(err: &SerializationError) -> &BuiltinTypeCheckError {
        match err.0.downcast_ref() {
            Some(err) => err,
            None => panic!("not a BuiltinTypeCheckError: {}", err),
        }
    }

    fn get_ser_err(err: &SerializationError) -> &BuiltinSerializationError {
        match err.0.downcast_ref() {
            Some(err) => err,
            None => panic!("not a BuiltinSerializationError: {}", err),
        }
    }

    #[test]
    fn test_native_errors() {
        // Simple type mismatch
        let v = 123_i32;
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<i32>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Int],
            },
        ));

        // str (and also Uuid) are interesting because they accept two types,
        // also check str here
        let v = "Ala ma kota";
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<&str>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Ascii, ColumnType::Text],
            },
        ));

        // We'll skip testing for SizeOverflow as this would require producing
        // a value which is at least 2GB in size.
    }

    #[cfg(feature = "bigdecimal-04")]
    #[test]
    fn test_native_errors_bigdecimal_04() {
        use bigdecimal_04::num_bigint::BigInt;
        use bigdecimal_04::BigDecimal;

        // Value overflow (type out of representable range)
        let v = BigDecimal::new(BigInt::from(123), 1i64 << 40);
        let err = do_serialize_err(v, &ColumnType::Decimal);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<BigDecimal>());
        assert_eq!(err.got, ColumnType::Decimal);
        assert!(matches!(
            err.kind,
            BuiltinSerializationErrorKind::ValueOverflow,
        ));
    }

    #[test]
    fn test_set_or_list_errors() {
        // Not a set or list
        let v = vec![123_i32];
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<Vec<i32>>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::SetOrListError(SetOrListTypeCheckErrorKind::NotSetOrList),
        ));

        // Trick: Unset is a ZST, so [Unset; 1 << 33] is a ZST, too.
        // While it's probably incorrect to use Unset in a collection, this
        // allows us to trigger the right error without going out of memory.
        // Such an array is also created instantaneously.
        let v = &[Unset; 1 << 33] as &[Unset];
        let typ = ColumnType::List(Box::new(ColumnType::Int));
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<&[Unset]>());
        assert_eq!(err.got, typ);
        assert!(matches!(
            err.kind,
            BuiltinSerializationErrorKind::SetOrListError(
                SetOrListSerializationErrorKind::TooManyElements
            ),
        ));

        // Error during serialization of an element
        let v = vec![123_i32];
        let typ = ColumnType::List(Box::new(ColumnType::Double));
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<Vec<i32>>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::SetOrListError(
            SetOrListSerializationErrorKind::ElementSerializationFailed(err),
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Int],
            }
        ));
    }

    #[test]
    fn test_map_errors() {
        // Not a map
        let v = BTreeMap::from([("foo", "bar")]);
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<BTreeMap<&str, &str>>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MapError(MapTypeCheckErrorKind::NotMap),
        ));

        // It's not practical to check the TooManyElements error as it would
        // require allocating a huge amount of memory.

        // Error during serialization of a key
        let v = BTreeMap::from([(123_i32, 456_i32)]);
        let typ = ColumnType::Map(Box::new(ColumnType::Double), Box::new(ColumnType::Int));
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<BTreeMap<i32, i32>>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::MapError(
            MapSerializationErrorKind::KeySerializationFailed(err),
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Int],
            }
        ));

        // Error during serialization of a value
        let v = BTreeMap::from([(123_i32, 456_i32)]);
        let typ = ColumnType::Map(Box::new(ColumnType::Int), Box::new(ColumnType::Double));
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<BTreeMap<i32, i32>>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::MapError(
            MapSerializationErrorKind::ValueSerializationFailed(err),
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Int],
            }
        ));
    }

    #[test]
    fn test_tuple_errors() {
        // Not a tuple
        let v = (123_i32, 456_i32, 789_i32);
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i32, i32, i32)>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::TupleError(TupleTypeCheckErrorKind::NotTuple),
        ));

        // The Rust tuple has more elements than the CQL type
        let v = (123_i32, 456_i32, 789_i32);
        let typ = ColumnType::Tuple(vec![ColumnType::Int; 2]);
        let err = do_serialize_err(v, &typ);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i32, i32, i32)>());
        assert_eq!(err.got, typ);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::TupleError(TupleTypeCheckErrorKind::WrongElementCount {
                actual: 3,
                asked_for: 2,
            }),
        ));

        // Error during serialization of one of the elements
        let v = (123_i32, "Ala ma kota", 789.0_f64);
        let typ = ColumnType::Tuple(vec![ColumnType::Int, ColumnType::Text, ColumnType::Uuid]);
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<(i32, &str, f64)>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::TupleError(
            TupleSerializationErrorKind::ElementSerializationFailed { index: 2, err },
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Double],
            }
        ));
    }

    #[test]
    fn test_cql_value_errors() {
        // Tried to encode Empty value into a non-emptyable type
        let v = CqlValue::Empty;
        let err = do_serialize_err(v, &ColumnType::Counter);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, ColumnType::Counter);
        assert!(matches!(err.kind, BuiltinTypeCheckErrorKind::NotEmptyable));

        // Handle tuples and UDTs in separate tests, as they have some
        // custom logic
    }

    #[test]
    fn test_cql_value_tuple_errors() {
        // Not a tuple
        let v = CqlValue::Tuple(vec![
            Some(CqlValue::Int(123_i32)),
            Some(CqlValue::Int(456_i32)),
            Some(CqlValue::Int(789_i32)),
        ]);
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::TupleError(TupleTypeCheckErrorKind::NotTuple),
        ));

        // The Rust tuple has more elements than the CQL type
        let v = CqlValue::Tuple(vec![
            Some(CqlValue::Int(123_i32)),
            Some(CqlValue::Int(456_i32)),
            Some(CqlValue::Int(789_i32)),
        ]);
        let typ = ColumnType::Tuple(vec![ColumnType::Int; 2]);
        let err = do_serialize_err(v, &typ);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, typ);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::TupleError(TupleTypeCheckErrorKind::WrongElementCount {
                actual: 3,
                asked_for: 2,
            }),
        ));

        // Error during serialization of one of the elements
        let v = CqlValue::Tuple(vec![
            Some(CqlValue::Int(123_i32)),
            Some(CqlValue::Text("Ala ma kota".to_string())),
            Some(CqlValue::Double(789_f64)),
        ]);
        let typ = ColumnType::Tuple(vec![ColumnType::Int, ColumnType::Text, ColumnType::Uuid]);
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::TupleError(
            TupleSerializationErrorKind::ElementSerializationFailed { index: 2, err },
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Double],
            }
        ));
    }

    #[test]
    fn test_cql_value_udt_errors() {
        // Not a UDT
        let v = CqlValue::UserDefinedType {
            keyspace: "ks".to_string(),
            type_name: "udt".to_string(),
            fields: vec![
                ("a".to_string(), Some(CqlValue::Int(123_i32))),
                ("b".to_string(), Some(CqlValue::Int(456_i32))),
                ("c".to_string(), Some(CqlValue::Int(789_i32))),
            ],
        };
        let err = do_serialize_err(v, &ColumnType::Double);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, ColumnType::Double);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NotUdt),
        ));

        // Wrong type name
        let v = CqlValue::UserDefinedType {
            keyspace: "ks".to_string(),
            type_name: "udt".to_string(),
            fields: vec![
                ("a".to_string(), Some(CqlValue::Int(123_i32))),
                ("b".to_string(), Some(CqlValue::Int(456_i32))),
                ("c".to_string(), Some(CqlValue::Int(789_i32))),
            ],
        };
        let typ = ColumnType::UserDefinedType {
            type_name: "udt2".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Int),
                ("b".to_string(), ColumnType::Int),
                ("c".to_string(), ColumnType::Int),
            ],
        };
        let err = do_serialize_err(v, &typ);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, typ);
        let BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NameMismatch {
            keyspace,
            type_name,
        }) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(keyspace, "ks");
        assert_eq!(type_name, "udt2");

        // Some fields are missing from the CQL type
        let v = CqlValue::UserDefinedType {
            keyspace: "ks".to_string(),
            type_name: "udt".to_string(),
            fields: vec![
                ("a".to_string(), Some(CqlValue::Int(123_i32))),
                ("b".to_string(), Some(CqlValue::Int(456_i32))),
                ("c".to_string(), Some(CqlValue::Int(789_i32))),
            ],
        };
        let typ = ColumnType::UserDefinedType {
            type_name: "udt".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Int),
                ("b".to_string(), ColumnType::Int),
                // c is missing
            ],
        };
        let err = do_serialize_err(v, &typ);
        let err = get_typeck_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, typ);
        let BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NoSuchFieldInUdt {
            field_name,
        }) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(field_name, "c");

        // It is allowed for a Rust UDT to have less fields than the CQL UDT,
        // so skip UnexpectedFieldInDestination.

        // Error during serialization of one of the fields
        let v = CqlValue::UserDefinedType {
            keyspace: "ks".to_string(),
            type_name: "udt".to_string(),
            fields: vec![
                ("a".to_string(), Some(CqlValue::Int(123_i32))),
                ("b".to_string(), Some(CqlValue::Int(456_i32))),
                ("c".to_string(), Some(CqlValue::Int(789_i32))),
            ],
        };
        let typ = ColumnType::UserDefinedType {
            type_name: "udt".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Int),
                ("b".to_string(), ColumnType::Int),
                ("c".to_string(), ColumnType::Double),
            ],
        };
        let err = do_serialize_err(v, &typ);
        let err = get_ser_err(&err);
        assert_eq!(err.rust_name, std::any::type_name::<CqlValue>());
        assert_eq!(err.got, typ);
        let BuiltinSerializationErrorKind::UdtError(
            UdtSerializationErrorKind::FieldSerializationFailed { field_name, err },
        ) = &err.kind
        else {
            panic!("unexpected error kind: {}", err.kind)
        };
        assert_eq!(field_name, "c");
        let err = get_typeck_err(err);
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::MismatchedType {
                expected: &[ColumnType::Int],
            }
        ));
    }

    // Do not remove. It's not used in tests but we keep it here to check that
    // we properly ignore warnings about unused variables, unnecessary `mut`s
    // etc. that usually pop up when generating code for empty structs.
    #[derive(SerializeCql)]
    #[scylla(crate = crate)]
    struct TestUdtWithNoFields {}

    #[derive(SerializeCql, Debug, PartialEq, Eq, Default)]
    #[scylla(crate = crate)]
    struct TestUdtWithFieldSorting {
        a: String,
        b: i32,
        c: Vec<i64>,
    }

    #[test]
    fn test_udt_serialization_with_field_sorting_correct_order() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let reference = do_serialize(
            CqlValue::UserDefinedType {
                keyspace: "ks".to_string(),
                type_name: "typ".to_string(),
                fields: vec![
                    (
                        "a".to_string(),
                        Some(CqlValue::Text(String::from("Ala ma kota"))),
                    ),
                    ("b".to_string(), Some(CqlValue::Int(42))),
                    (
                        "c".to_string(),
                        Some(CqlValue::List(vec![
                            CqlValue::BigInt(1),
                            CqlValue::BigInt(2),
                            CqlValue::BigInt(3),
                        ])),
                    ),
                ],
            },
            &typ,
        );
        let udt = do_serialize(
            TestUdtWithFieldSorting {
                a: "Ala ma kota".to_owned(),
                b: 42,
                c: vec![1, 2, 3],
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[test]
    fn test_udt_serialization_with_field_sorting_incorrect_order() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                // Two first columns are swapped
                ("b".to_string(), ColumnType::Int),
                ("a".to_string(), ColumnType::Text),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let reference = do_serialize(
            CqlValue::UserDefinedType {
                keyspace: "ks".to_string(),
                type_name: "typ".to_string(),
                fields: vec![
                    // FIXME: UDTs in CqlValue should also honor the order
                    // For now, it's swapped here as well
                    ("b".to_string(), Some(CqlValue::Int(42))),
                    (
                        "a".to_string(),
                        Some(CqlValue::Text(String::from("Ala ma kota"))),
                    ),
                    (
                        "c".to_string(),
                        Some(CqlValue::List(vec![
                            CqlValue::BigInt(1),
                            CqlValue::BigInt(2),
                            CqlValue::BigInt(3),
                        ])),
                    ),
                ],
            },
            &typ,
        );
        let udt = do_serialize(
            TestUdtWithFieldSorting {
                a: "Ala ma kota".to_owned(),
                b: 42,
                c: vec![1, 2, 3],
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[test]
    fn test_udt_serialization_with_missing_rust_fields_at_end() {
        let udt = TestUdtWithFieldSorting::default();

        let typ_normal = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let typ_unexpected_field = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
                // Unexpected fields
                ("d".to_string(), ColumnType::Counter),
                ("e".to_string(), ColumnType::Counter),
            ],
        };

        let result_normal = do_serialize(&udt, &typ_normal);
        let result_additional_field = do_serialize(&udt, &typ_unexpected_field);

        assert_eq!(result_normal, result_additional_field);
    }

    #[derive(SerializeCql, Debug, PartialEq, Default)]
    #[scylla(crate = crate)]
    struct TestUdtWithFieldSorting2 {
        a: String,
        b: i32,
        d: Option<Counter>,
        c: Vec<i64>,
    }

    #[derive(SerializeCql, Debug, PartialEq, Default)]
    #[scylla(crate = crate)]
    struct TestUdtWithFieldSorting3 {
        a: String,
        b: i32,
        d: Option<Counter>,
        e: Option<f32>,
        c: Vec<i64>,
    }

    #[test]
    fn test_udt_serialization_with_missing_rust_field_in_middle() {
        let udt = TestUdtWithFieldSorting::default();
        let udt2 = TestUdtWithFieldSorting2::default();
        let udt3 = TestUdtWithFieldSorting3::default();

        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                // Unexpected fields
                ("d".to_string(), ColumnType::Counter),
                ("e".to_string(), ColumnType::Float),
                // Remaining normal field
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let result_1 = do_serialize(udt, &typ);
        let result_2 = do_serialize(udt2, &typ);
        let result_3 = do_serialize(udt3, &typ);

        assert_eq!(result_1, result_2);
        assert_eq!(result_2, result_3);
    }

    #[test]
    fn test_udt_serialization_failing_type_check() {
        let typ_not_udt = ColumnType::Ascii;
        let udt = TestUdtWithFieldSorting::default();
        let mut data = Vec::new();

        let err = udt
            .serialize(&typ_not_udt, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NotUdt)
        ));

        let typ_without_c = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                // Last field is missing
            ],
        };

        let err = udt
            .serialize(&typ_without_c, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(
                UdtTypeCheckErrorKind::ValueMissingForUdtField { .. }
            )
        ));

        let typ_wrong_type = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                ("c".to_string(), ColumnType::TinyInt), // Wrong column type
            ],
        };

        let err = udt
            .serialize(&typ_wrong_type, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinSerializationError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinSerializationErrorKind::UdtError(
                UdtSerializationErrorKind::FieldSerializationFailed { .. }
            )
        ));
    }

    #[derive(SerializeCql)]
    #[scylla(crate = crate)]
    struct TestUdtWithGenerics<'a, T: SerializeCql> {
        a: &'a str,
        b: T,
    }

    #[test]
    fn test_udt_serialization_with_generics() {
        // A minimal smoke test just to test that it works.
        fn check_with_type<T: SerializeCql>(typ: ColumnType, t: T, cql_t: CqlValue) {
            let typ = ColumnType::UserDefinedType {
                type_name: "typ".to_string(),
                keyspace: "ks".to_string(),
                field_types: vec![("a".to_string(), ColumnType::Text), ("b".to_string(), typ)],
            };
            let reference = do_serialize(
                CqlValue::UserDefinedType {
                    keyspace: "ks".to_string(),
                    type_name: "typ".to_string(),
                    fields: vec![
                        (
                            "a".to_string(),
                            Some(CqlValue::Text(String::from("Ala ma kota"))),
                        ),
                        ("b".to_string(), Some(cql_t)),
                    ],
                },
                &typ,
            );
            let udt = do_serialize(
                TestUdtWithGenerics {
                    a: "Ala ma kota",
                    b: t,
                },
                &typ,
            );
            assert_eq!(reference, udt);
        }

        check_with_type(ColumnType::Int, 123_i32, CqlValue::Int(123_i32));
        check_with_type(ColumnType::Double, 123_f64, CqlValue::Double(123_f64));
    }

    #[derive(SerializeCql, Debug, PartialEq, Eq, Default)]
    #[scylla(crate = crate, flavor = "enforce_order")]
    struct TestUdtWithEnforcedOrder {
        a: String,
        b: i32,
        c: Vec<i64>,
    }

    #[test]
    fn test_udt_serialization_with_enforced_order_correct_order() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let reference = do_serialize(
            CqlValue::UserDefinedType {
                keyspace: "ks".to_string(),
                type_name: "typ".to_string(),
                fields: vec![
                    (
                        "a".to_string(),
                        Some(CqlValue::Text(String::from("Ala ma kota"))),
                    ),
                    ("b".to_string(), Some(CqlValue::Int(42))),
                    (
                        "c".to_string(),
                        Some(CqlValue::List(vec![
                            CqlValue::BigInt(1),
                            CqlValue::BigInt(2),
                            CqlValue::BigInt(3),
                        ])),
                    ),
                ],
            },
            &typ,
        );
        let udt = do_serialize(
            TestUdtWithEnforcedOrder {
                a: "Ala ma kota".to_owned(),
                b: 42,
                c: vec![1, 2, 3],
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[test]
    fn test_udt_serialization_with_enforced_order_additional_field() {
        let udt = TestUdtWithEnforcedOrder::default();

        let typ_normal = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let typ_unexpected_field = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
                // Unexpected field
                ("d".to_string(), ColumnType::Counter),
            ],
        };

        let result_normal = do_serialize(&udt, &typ_normal);
        let result_additional_field = do_serialize(&udt, &typ_unexpected_field);

        assert_eq!(result_normal, result_additional_field);
    }

    #[test]
    fn test_udt_serialization_with_enforced_order_failing_type_check() {
        let typ_not_udt = ColumnType::Ascii;
        let udt = TestUdtWithEnforcedOrder::default();

        let mut data = Vec::new();

        let err = <_ as SerializeCql>::serialize(&udt, &typ_not_udt, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NotUdt)
        ));

        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                // Two first columns are swapped
                ("b".to_string(), ColumnType::Int),
                ("a".to_string(), ColumnType::Text),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let err =
            <_ as SerializeCql>::serialize(&udt, &typ, CellWriter::new(&mut data)).unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::FieldNameMismatch { .. })
        ));

        let typ_without_c = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                // Last field is missing
            ],
        };

        let err = <_ as SerializeCql>::serialize(&udt, &typ_without_c, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(
                UdtTypeCheckErrorKind::ValueMissingForUdtField { .. }
            )
        ));

        let typ_unexpected_field = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                ("c".to_string(), ColumnType::TinyInt), // Wrong column type
            ],
        };

        let err =
            <_ as SerializeCql>::serialize(&udt, &typ_unexpected_field, CellWriter::new(&mut data))
                .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinSerializationError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinSerializationErrorKind::UdtError(
                UdtSerializationErrorKind::FieldSerializationFailed { .. }
            )
        ));
    }

    #[derive(SerializeCql, Debug)]
    #[scylla(crate = crate)]
    struct TestUdtWithFieldRename {
        a: String,
        #[scylla(rename = "x")]
        b: i32,
    }

    #[derive(SerializeCql, Debug)]
    #[scylla(crate = crate, flavor = "enforce_order")]
    struct TestUdtWithFieldRenameAndEnforceOrder {
        a: String,
        #[scylla(rename = "x")]
        b: i32,
    }

    #[test]
    fn test_udt_serialization_with_field_rename() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("x".to_string(), ColumnType::Int),
                ("a".to_string(), ColumnType::Text),
            ],
        };

        let mut reference = Vec::new();
        // Total length of the struct is 23
        reference.extend_from_slice(&23i32.to_be_bytes());
        // Field 'x'
        reference.extend_from_slice(&4i32.to_be_bytes());
        reference.extend_from_slice(&42i32.to_be_bytes());
        // Field 'a'
        reference.extend_from_slice(&("Ala ma kota".len() as i32).to_be_bytes());
        reference.extend_from_slice("Ala ma kota".as_bytes());

        let udt = do_serialize(
            TestUdtWithFieldRename {
                a: "Ala ma kota".to_owned(),
                b: 42,
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[test]
    fn test_udt_serialization_with_field_rename_and_enforce_order() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("x".to_string(), ColumnType::Int),
            ],
        };

        let mut reference = Vec::new();
        // Total length of the struct is 23
        reference.extend_from_slice(&23i32.to_be_bytes());
        // Field 'a'
        reference.extend_from_slice(&("Ala ma kota".len() as i32).to_be_bytes());
        reference.extend_from_slice("Ala ma kota".as_bytes());
        // Field 'x'
        reference.extend_from_slice(&4i32.to_be_bytes());
        reference.extend_from_slice(&42i32.to_be_bytes());

        let udt = do_serialize(
            TestUdtWithFieldRenameAndEnforceOrder {
                a: "Ala ma kota".to_owned(),
                b: 42,
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[derive(SerializeCql, Debug)]
    #[scylla(crate = crate, flavor = "enforce_order", skip_name_checks)]
    struct TestUdtWithSkippedNameChecks {
        a: String,
        b: i32,
    }

    #[test]
    fn test_udt_serialization_with_skipped_name_checks() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("x".to_string(), ColumnType::Int),
            ],
        };

        let mut reference = Vec::new();
        // Total length of the struct is 23
        reference.extend_from_slice(&23i32.to_be_bytes());
        // Field 'a'
        reference.extend_from_slice(&("Ala ma kota".len() as i32).to_be_bytes());
        reference.extend_from_slice("Ala ma kota".as_bytes());
        // Field 'x'
        reference.extend_from_slice(&4i32.to_be_bytes());
        reference.extend_from_slice(&42i32.to_be_bytes());

        let udt = do_serialize(
            TestUdtWithFieldRenameAndEnforceOrder {
                a: "Ala ma kota".to_owned(),
                b: 42,
            },
            &typ,
        );

        assert_eq!(reference, udt);
    }

    #[derive(SerializeCql, Debug, PartialEq, Eq, Default)]
    #[scylla(crate = crate, force_exact_match)]
    struct TestStrictUdtWithFieldSorting {
        a: String,
        b: i32,
        c: Vec<i64>,
    }

    #[test]
    fn test_strict_udt_with_field_sorting_rejects_additional_field() {
        let udt = TestStrictUdtWithFieldSorting::default();
        let mut data = Vec::new();

        let typ_unexpected_field = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
                // Unexpected field
                ("d".to_string(), ColumnType::Counter),
            ],
        };

        let err = udt
            .serialize(&typ_unexpected_field, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NoSuchFieldInUdt { .. })
        ));

        let typ_unexpected_field_middle = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                // Unexpected field
                ("b_c".to_string(), ColumnType::Counter),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let err = udt
            .serialize(&typ_unexpected_field_middle, CellWriter::new(&mut data))
            .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NoSuchFieldInUdt { .. })
        ));
    }

    #[derive(SerializeCql, Debug, PartialEq, Eq, Default)]
    #[scylla(crate = crate, flavor = "enforce_order", force_exact_match)]
    struct TestStrictUdtWithEnforcedOrder {
        a: String,
        b: i32,
        c: Vec<i64>,
    }

    #[test]
    fn test_strict_udt_with_enforced_order_rejects_additional_field() {
        let udt = TestStrictUdtWithEnforcedOrder::default();
        let mut data = Vec::new();

        let typ_unexpected_field = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
                // Unexpected field
                ("d".to_string(), ColumnType::Counter),
            ],
        };

        let err =
            <_ as SerializeCql>::serialize(&udt, &typ_unexpected_field, CellWriter::new(&mut data))
                .unwrap_err();
        let err = err.0.downcast_ref::<BuiltinTypeCheckError>().unwrap();
        assert!(matches!(
            err.kind,
            BuiltinTypeCheckErrorKind::UdtError(UdtTypeCheckErrorKind::NoSuchFieldInUdt { .. })
        ));
    }

    #[derive(SerializeCql, Debug)]
    #[scylla(crate = crate, flavor = "enforce_order", skip_name_checks)]
    struct TestUdtWithSkippedFields {
        a: String,
        b: i32,
        #[scylla(skip)]
        #[allow(dead_code)]
        skipped: Vec<String>,
        c: Vec<i64>,
    }

    #[test]
    fn test_row_serialization_with_skipped_field() {
        let typ = ColumnType::UserDefinedType {
            type_name: "typ".to_string(),
            keyspace: "ks".to_string(),
            field_types: vec![
                ("a".to_string(), ColumnType::Text),
                ("b".to_string(), ColumnType::Int),
                (
                    "c".to_string(),
                    ColumnType::List(Box::new(ColumnType::BigInt)),
                ),
            ],
        };

        let reference = do_serialize(
            TestUdtWithFieldSorting {
                a: "Ala ma kota".to_owned(),
                b: 42,
                c: vec![1, 2, 3],
            },
            &typ,
        );
        let row = do_serialize(
            TestUdtWithSkippedFields {
                a: "Ala ma kota".to_owned(),
                b: 42,
                skipped: vec!["abcd".to_owned(), "efgh".to_owned()],
                c: vec![1, 2, 3],
            },
            &typ,
        );

        assert_eq!(reference, row);
    }
}