arzmq 0.6.2

High-level bindings to the zeromq library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
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
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
//! # 0MQ sockets
//!
//! Sockets are the main entry point to interact with other 0MQ sockets. They come in different
//! [`SocketType`]s for interactions.
//!
//! # Key differences to conventional sockets
//! Generally speaking, conventional sockets present a synchronous interface to either
//! connection-oriented reliable byte streams (SOCK_STREAM), or connection-less unreliable
//! datagrams (SOCK_DGRAM). In comparison, 0MQ sockets present an abstraction of an asynchronous
//! message queue, with the exact queueing semantics depending on the socket type in use. Where
//! conventional sockets transfer streams of bytes or discrete datagrams, 0MQ sockets transfer
//! discrete messages.
//!
//! 0MQ sockets being asynchronous means that the timings of the physical connection setup and tear
//! down, reconnect and effective delivery are transparent to the user and organized by 0MQ itself.
//! Further, messages may be queued in the event that a peer is unavailable to receive them.
//!
//! Conventional sockets allow only strict one-to-one (two peers), many-to-one (many clients, one
//! server), or in some cases one-to-many (multicast) relationships. With the exception of
//! [`Pair`] and [`Channel`], 0MQ sockets may be connected to multiple endpoints using
//! [`connect()`], while simultaneously accepting incoming connections from multiple endpoints
//! bound to the socket using [`bind()`], thus allowing many-to-many relationships.
//!
//! # Socket types
//! The following sections present the socket types defined by 0MQ, grouped by the general
//! messaging pattern which is built from related socket types.
//!
//! [`SocketType`]: SocketType
//! [`Pair`]: PairSocket
//! [`Channel`]: ChannelSocket
//! [`connect()`]: Socket::connect
//! [`bind()`]: Socket::bind
//!
//! ## Publish-Subscribe pattern
//! The publish-subscribe pattern is used for one-to-many distribution of data from a single
//! [`Publish`]er to multiple [`Subscribe`]ers in a fan out fashion.
//!
//! ### Examples:
//! Publish-Subscribe:
//! ```
//! # use core::sync::atomic::{Ordering, AtomicBool};
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, PublishSocket, SubscribeSocket, Sender, SendFlags, Receiver, RecvFlags};
//! #
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! const SUBSCRIBED_TOPIC: &str = "arzmq-example";
//!
//! pub fn run_publisher<S>(socket: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender,
//! {
//!     while KEEP_RUNNING.load(Ordering::Acquire) {
//!         socket.send_msg(msg, SendFlags::empty())?;
//!     }
//!
//!     Ok(())
//! }
//!
//! pub fn run_subscribe_client<S>(socket: &S, subscribed_topic: &str) -> ZmqResult<()>
//! where
//!    S: Receiver,
//! {
//!     let zmq_msg = socket.recv_msg(RecvFlags::empty())?;
//!     let zmq_str = zmq_msg.to_string();
//!     let pubsub_item = zmq_str.split_once(" ");
//!     assert_eq!(Some((subscribed_topic, "important update")), pubsub_item);
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let publish = PublishSocket::from_context(&context)?;
//!     publish.bind("tcp://127.0.0.1:*")?;
//!     let subscribe_endpoint = publish.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         let published_msg = format!("{SUBSCRIBED_TOPIC} important update");
//!         run_publisher(&publish, &published_msg).unwrap();
//!     });
//!
//!     let subscribe = SubscribeSocket::from_context(&context)?;
//!     subscribe.connect(subscribe_endpoint)?;
//!     subscribe.subscribe(SUBSCRIBED_TOPIC)?;
//!
//!     (0..iterations).try_for_each(|number| {
//!         run_subscribe_client(&subscribe, SUBSCRIBED_TOPIC)
//!     })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! ```
//!
//! XPublish-XSubscribe:
//! ```
//! # use core::sync::atomic::{Ordering, AtomicBool};
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, Receiver, RecvFlags, SendFlags, Sender, XPublishSocket, XSubscribeSocket};
//! #
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! const SUBSCRIBED_TOPIC: &str = "arzmq-example";
//!
//! fn run_xpublish_socket(xpublish: &XPublishSocket, msg: &str) -> ZmqResult<()> {
//!     while KEEP_RUNNING.load(Ordering::Acquire) {
//!         let published_msg = format!("{SUBSCRIBED_TOPIC} {msg}");
//!         xpublish.send_msg(&published_msg, SendFlags::empty())?;
//!     }
//!
//!     Ok(())
//! }
//!
//! pub fn run_subscribe_client<S>(socket: &S, subscribed_topic: &str) -> ZmqResult<()>
//! where
//!    S: Receiver,
//! {
//!     let zmq_msg = socket.recv_msg(RecvFlags::empty())?;
//!     let zmq_str = zmq_msg.to_string();
//!     let pubsub_item = zmq_str.split_once(" ");
//!     assert_eq!(Some((subscribed_topic, "important update")), pubsub_item);
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let xpublish = XPublishSocket::from_context(&context)?;
//!     xpublish.bind("tcp://127.0.0.1:*")?;
//!     let xsubscribe_endpoint = xpublish.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         run_xpublish_socket(&xpublish, "important update").unwrap();
//!     });
//!
//!     let xsubscribe = XSubscribeSocket::from_context(&context)?;
//!     xsubscribe.connect(xsubscribe_endpoint)?;
//!     xsubscribe.subscribe(SUBSCRIBED_TOPIC)?;
//!
//!     (0..iterations).try_for_each(|number| {
//!         run_subscribe_client(&xsubscribe, SUBSCRIBED_TOPIC)
//!     })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! ```
//!
//! [`Publish`]: PublishSocket
//! [`Subscribe`]: SubscribeSocket
//!
//! ## Client-Server pattern <span class="stab portability"><code>draft-api</code></span>
//! The client-server pattern is used to allow a single [`Server`] server talk to one or more
//! [`Client`] clients. The client always starts the conversation, after which either peer can send
//! messages asynchronously, to the other.
//!
//! ### Examples:
//! ```
//! # #[cfg(feature = "draft-api")]
//! # use core::sync::atomic::{AtomicBool, Ordering};
//! # #[cfg(feature = "draft-api")]
//! # use std::thread;
//! #
//! # #[cfg(feature = "draft-api")]
//! # use arzmq::prelude::{ZmqError, ZmqResult, Context, Message, ClientSocket, Receiver, RecvFlags, SendFlags, Sender, ServerSocket};
//! #
//! # #[cfg(feature = "draft-api")]
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! # #[cfg(feature = "draft-api")]
//! fn run_server_socket(server: &ServerSocket, reply: &str) -> ZmqResult<()> {
//!     while KEEP_RUNNING.load(Ordering::Acquire) {
//!         let message = server.recv_msg(RecvFlags::empty())?;
//!         assert_eq!(message.to_string(), "Hello");
//!
//!         let returned: Message = reply.into();
//!         returned.set_routing_id(message.routing_id().unwrap())?;
//!         server.send_msg(returned, SendFlags::empty())?;
//!     }
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! pub fn run_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender + Receiver,
//! {
//!     send_recv.send_msg(msg, SendFlags::empty())?;
//!
//!     let message = send_recv.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let server = ServerSocket::from_context(&context)?;
//!     server.bind("tcp://127.0.0.1:*")?;
//!     let client_endpoint = server.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!             run_server_socket(&server, "World").unwrap();
//!     });
//!
//!     let client = ClientSocket::from_context(&context)?;
//!     client.connect(client_endpoint)?;
//!
//!     (0..iterations).try_for_each(|number| {
//!         run_send_recv(&client, "Hello")
//!      })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! # #[cfg(not(feature = "draft-api"))]
//! # fn main() {}
//! ```
//!
//! [`Server`]: ServerSocket
//! [`Client`]: ClientSocket
//!
//! ## Radio-Dish pattern <span class="stab portability"><code>draft-api</code></span>
//!
//! The radio-dish pattern is used for one-to-many distribution of data from a single publisher to
//! multiple subscribers in a fan out fashion.
//!
//! Radio-dish is using groups (vs Pub-sub topics), [`Dish`] sockets can #[`join()`] a group and
//! each message sent by [´Radio´] sockets belong to a group.
//!
//! Groups are null terminated strings limited to 16 chars length (including null). The intention
//! is to increase the length to 40 chars (including null). The encoding of groups shall be UTF8.
//!
//! ### Example
//!
//! ```
//! # #[cfg(feature = "draft-api")]
//! # use core::sync::atomic::{AtomicBool, Ordering};
//! # #[cfg(feature = "draft-api")]
//! # use std::thread;
//! #
//! # #[cfg(feature = "draft-api")]
//! # use arzmq::prelude::{ZmqError, ZmqResult, Context, Message, DishSocket, RadioSocket, Receiver, RecvFlags, SendFlags, Sender};
//! #
//! # #[cfg(feature = "draft-api")]
//! static GROUP: &str = "radio-dish-ex";
//!
//! # #[cfg(feature = "draft-api")]
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! # #[cfg(feature = "draft-api")]
//! fn run_radio_socket(radio: &RadioSocket, message: &str) -> ZmqResult<()> {
//!     while KEEP_RUNNING.load(Ordering::Acquire) {
//!         let msg: Message = message.into();
//!         msg.set_group(GROUP).unwrap();
//!
//!         radio.send_msg(msg, SendFlags::empty()).unwrap();
//!     }
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let radio = RadioSocket::from_context(&context)?;
//!     radio.bind("tcp://127.0.0.1:*")?;
//!     let dish_endpoint = radio.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         run_radio_socket(&radio, "radio msg").unwrap();
//!     });
//!
//!     let dish = DishSocket::from_context(&context)?;
//!     dish.connect(dish_endpoint)?;
//!     dish.join(GROUP)?;
//!
//!     (0..iterations).try_for_each(|_| {
//!         let msg = dish.recv_msg(RecvFlags::empty())?;
//!         assert_eq!(msg.to_string(), "radio msg");
//!         Ok::<(), ZmqError>(())
//!     })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! # #[cfg(not(feature = "draft-api"))]
//! # fn main() {}
//! ```
//!
//! [`Radio`]: RadioSocket
//! [`Dish`]: DishSocket
//! [`join()`]: DishSocket::join
//!
//! ## Pipeline pattern ([`Push`]/[`Pull`])
//! The pipeline pattern is used for distributing data to nodes arranged in a pipeline. Data always
//! flows down the pipeline, and each stage of the pipeline is connected to at least one node. When
//! a pipeline stage is connected to multiple nodes data is round-robined among all connected nodes
//!
//! ### Example
//! ```
//! # use core::sync::atomic::{Ordering, AtomicBool};
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqError, ZmqResult, Context, PullSocket, PushSocket, Sender, SendFlags, Receiver, RecvFlags};
//! #
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let push = PushSocket::from_context(&context)?;
//!     push.bind("tcp://127.0.0.1:*")?;
//!     let pull_endpoint = push.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         while KEEP_RUNNING.load(Ordering::Acquire) {
//!             push.send_msg("important update", SendFlags::empty()).unwrap();
//!         }
//!     });
//!
//!     let pull = PullSocket::from_context(&context)?;
//!     pull.connect(pull_endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| {
//!         let msg = pull.recv_msg(RecvFlags::empty())?;
//!         assert_eq!(msg.to_string(), "important update");
//!
//!         Ok::<(), ZmqError>(())
//!     })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! ```
//!
//! [`Push`]: PushSocket
//! [`Pull`]: PullSocket
//!
//! ## Scatter-gather pattern <span class="stab portability"><code>draft-api</code></span>
//! The [`Scatter`]-[`Gather`] pattern is the thread-safe version of the pipeline pattern. The
//! scatter-gather pattern is used for distributing data to nodes arranged in a pipeline. Data
//! always flows down the pipeline, and each stage of the pipeline is connected to at least one
//! node. When a pipeline stage is connected to multiple nodes data is round-robined among all
//! connected nodes.
//!
//! ### Example
//! ```
//! # #[cfg(feature = "draft-api")]
//! # use core::sync::atomic::{AtomicBool, Ordering};
//! # #[cfg(feature = "draft-api")]
//! # use std::thread;
//! #
//! # #[cfg(feature = "draft-api")]
//! # use arzmq::prelude::{ZmqResult, ZmqError, Context, GatherSocket, Receiver, RecvFlags, ScatterSocket, SendFlags, Sender};
//! #
//! # #[cfg(feature = "draft-api")]
//! static KEEP_RUNNING: AtomicBool = AtomicBool::new(true);
//!
//! # #[cfg(feature = "draft-api")]
//! pub fn run_publisher<S>(socket: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender,
//! {
//!     while KEEP_RUNNING.load(Ordering::Acquire) {
//!         socket.send_msg(msg, SendFlags::empty())?;
//!     }
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let scatter = ScatterSocket::from_context(&context)?;
//!     scatter.bind("tcp://127.0.0.1:*")?;
//!     let gather_endpoint = scatter.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         run_publisher(&scatter, "important update").unwrap();
//!     });
//!
//!     let gather = GatherSocket::from_context(&context)?;
//!     gather.connect(gather_endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| {
//!         let msg = gather.recv_msg(RecvFlags::empty())?;
//!         assert_eq!(msg.to_string(), "important update");
//!
//!         Ok::<(), ZmqError>(())
//!     })?;
//!
//!     KEEP_RUNNING.store(false, Ordering::Release);
//!
//!     Ok(())
//! }
//! # #[cfg(not(feature = "draft-api"))]
//! # fn main() {}
//! ```
//!
//! [`Scatter`]: ScatterSocket
//! [`Gather`]: GatherSocket
//!
//! ## Exclusive pair pattern
//! The exclusive [`Pair`] pattern is used to connect a peer to precisely one other peer. This pattern
//! is used for inter-thread communication across the inproc transport.
//!
//! ### Example
//! ```
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, PairSocket, Sender, Receiver, SendFlags, RecvFlags};
//! #
//! pub fn run_recv_send<S>(recv_send: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Receiver + Sender,
//! {
//!     let message = recv_send.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "Hello");
//!
//!     recv_send.send_msg(msg, SendFlags::empty())
//! }
//!
//! pub fn run_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender + Receiver,
//! {
//!     send_recv.send_msg(msg, SendFlags::empty())?;
//!
//!     let message = send_recv.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let endpoint = "inproc://arzmq-example-pair";
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let pair_server = PairSocket::from_context(&context)?;
//!     pair_server.bind(endpoint)?;
//!
//!     thread::spawn(move || {
//!         (0..iterations)
//!             .try_for_each(|_| run_recv_send(&pair_server, "World"))
//!             .unwrap();
//!     });
//!
//!     let pair_client = PairSocket::from_context(&context)?;
//!     pair_client.connect(endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_send_recv(&pair_client, "Hello"))
//! }
//! ```
//!
//! [`Pair`]: PairSocket
//!
//! ## Peer-to-peer pattern <span class="stab portability"><code>draft-api</code></span>
//! The peer-to-peer pattern is used to connect a [`Peer`] to multiple peers. Peer can both connect
//! and bind and mix both of them with the same socket. The peer-to-peer pattern is useful to build
//! peer-to-peer networks (e.g zyre, bitcoin, torrent) where a peer can both accept connections
//! from other peers or connect to them.
//!
//! ### Example
//! ```
//! # #[cfg(feature = "draft-api")]
//! # use std::thread;
//! #
//! # #[cfg(feature = "draft-api")]
//! # use arzmq::prelude::{ZmqResult, Context, Message, PeerSocket, Receiver, RecvFlags, SendFlags, Sender};
//! #
//! # #[cfg(feature = "draft-api")]
//! fn run_peer_server(peer: &PeerSocket, msg: &str) -> ZmqResult<()> {
//!     let message = peer.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "Hello");
//!
//!     let response: Message = msg.into();
//!     response.set_routing_id(message.routing_id().unwrap())?;
//!     peer.send_msg(response, SendFlags::empty())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn run_peer_client(peer: &PeerSocket, routing_id: u32, msg: &str) -> ZmqResult<()> {
//!     let request: Message = msg.into();
//!     request.set_routing_id(routing_id)?;
//!     peer.send_msg(request, SendFlags::empty())?;
//!
//!     let message = peer.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn main() -> ZmqResult<()> {
//!     let endpoint = "inproc://arzmq-example-peer";
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let peer_server = PeerSocket::from_context(&context)?;
//!     peer_server.bind(endpoint)?;
//!
//!     thread::spawn(move || {
//!         (0..iterations).try_for_each(|_| {
//!             run_peer_server(&peer_server, "World")
//!         }).unwrap();
//!     });
//!
//!     let peer_client = PeerSocket::from_context(&context)?;
//!     let routing_id = peer_client.connect_peer(endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_peer_client(&peer_client, routing_id, "Hello"))
//! }
//! # #[cfg(not(feature = "draft-api"))]
//! # fn main() {}
//! ```
//!
//! [`Peer`]: PeerSocket
//!
//! ## Channel pattern <span class="stab portability"><code>draft-api</code></span>
//! The [`Channel`] pattern is the thread-safe version of the exclusive [`Pair`] pattern. The
//! channel pattern is used to connect a peer to precisely one other peer. This pattern is used for
//! inter-thread communication across the inproc transport.
//!
//! ### Example
//! ```
//! # #[cfg(feature = "draft-api")]
//! # use std::thread;
//! #
//! # #[cfg(feature = "draft-api")]
//! # use arzmq::prelude::{ZmqResult, Context, ChannelSocket, Sender, Receiver, SendFlags, RecvFlags};
//! #
//! # #[cfg(feature = "draft-api")]
//! pub fn run_recv_send<S>(recv_send: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Receiver + Sender,
//! {
//!     let message = recv_send.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "Hello");
//!
//!     recv_send.send_msg(msg, SendFlags::empty())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! pub fn run_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender + Receiver,
//! {
//!     send_recv.send_msg(msg, SendFlags::empty())?;
//!
//!     let message = send_recv.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! # #[cfg(feature = "draft-api")]
//! fn main() -> ZmqResult<()> {
//!     let endpoint = "inproc://arzmq-example-channel";
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let channel_server = ChannelSocket::from_context(&context)?;
//!     channel_server.bind(endpoint)?;
//!
//!     thread::spawn(move || {
//!         (0..iterations)
//!             .try_for_each(|_| run_recv_send(&channel_server, "World"))
//!             .unwrap();
//!     });
//!
//!     let channel_client = ChannelSocket::from_context(&context)?;
//!     channel_client.connect(endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_send_recv(&channel_client, "Hello"))
//! }
//! # #[cfg(not(feature = "draft-api"))]
//! # fn main() {}
//! ```
//!
//! [`Channel`]: ChannelSocket
//! [`Pair`]: PairSocket
//!
//! ## Native pattern ([`Stream`])
//! The native pattern is used for communicating with TCP peers and allows asynchronous requests
//! and replies in either direction.
//!
//! ### Example
//! Stream as client:
//! ```
//! # #[rustversion::since(1.87)]
//! # use core::str;
//! # use core::error::Error;
//! # #[rustversion::before(1.87)]
//! # use std::str;
//! # use std::{io::prelude::*, net::TcpListener, thread};
//! #
//! # use arzmq::prelude::{ZmqResult, Context, MultipartMessage, MultipartReceiver, MultipartSender, RecvFlags, SendFlags, StreamSocket};
//! #
//! fn run_tcp_server(endpoint: &str) -> Result<(), Box<dyn Error>> {
//!     let tcp_listener = TcpListener::bind(endpoint)?;
//!     thread::spawn(move || {
//!         let (mut tcp_stream, _socket_addr) = tcp_listener.accept().unwrap();
//!         tcp_stream.write_all("".as_bytes()).unwrap();
//!         loop {
//!             let mut buffer = [0; 256];
//!             if let Ok(length) = tcp_stream.read(&mut buffer) {
//!                 if length == 0 {
//!                     break;
//!                 }
//!                 let recevied_msg = &buffer[..length];
//!                 assert_eq!(str::from_utf8(recevied_msg).unwrap(), "Hello");
//!                 tcp_stream.write_all("World".as_bytes()).unwrap();
//!             }
//!         }
//!     });
//!
//!     Ok(())
//! }
//!
//! fn run_stream_socket(zmq_stream: &StreamSocket, routing_id: &[u8], msg: &str) -> ZmqResult<()> {
//!     let mut multipart = MultipartMessage::new();
//!     multipart.push_back(routing_id.into());
//!     multipart.push_back(msg.into());
//!     zmq_stream.send_multipart(multipart, SendFlags::empty())?;
//!
//!     let mut message = zmq_stream.recv_multipart(RecvFlags::empty())?;
//!     assert_eq!(message.pop_back().unwrap().to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!     let port = 5558;
//!     let iterations = 10;
//!
//!     let tcp_endpoint = format!("127.0.0.1:{port}");
//!     run_tcp_server(&tcp_endpoint)?;
//!
//!     let context = Context::new()?;
//!
//!     let zmq_stream = StreamSocket::from_context(&context)?;
//!
//!     let stream_endpoint = format!("tcp://127.0.0.1:{port}");
//!     zmq_stream.connect(stream_endpoint)?;
//!
//!     let mut connect_msg = zmq_stream.recv_multipart(RecvFlags::empty())?;
//!     let routing_id = connect_msg.pop_front().unwrap();
//!
//!     (0..iterations)
//!         .try_for_each(|_| run_stream_socket(&zmq_stream, &routing_id.bytes(), "Hello"))?;
//!
//!     Ok(())
//! }
//! ```
//!
//! Stream as server:
//! ```
//! # #[rustversion::since(1.87)]
//! # use core::str;
//! # use core::error::Error;
//! # #[rustversion::before(1.87)]
//! # use std::str;
//! # use std::{io::prelude::*, net::TcpStream, thread};
//! #
//! # use arzmq::prelude::{ZmqResult, Context, MultipartReceiver, MultipartSender, RecvFlags, SendFlags, StreamSocket};
//! #
//! fn run_stream_socket(zmq_stream: &StreamSocket, _routing_id: &[u8], msg: &str) -> ZmqResult<()> {
//!     let mut message = zmq_stream.recv_multipart(RecvFlags::empty())?;
//!     assert_eq!(message.pop_back().unwrap().to_string(), "Hello");
//!
//!     message.push_back(msg.into());
//!     zmq_stream.send_multipart(message, SendFlags::empty())
//! }
//!
//! fn run_tcp_client(endpoint: &str, iterations: i32) -> Result<(), Box<dyn Error>> {
//!     let mut tcp_stream = TcpStream::connect(endpoint)?;
//!     (0..iterations).try_for_each(|request_no| {
//!         println!("Sending requrst {request_no}");
//!         tcp_stream.write_all("Hello".as_bytes()).unwrap();
//!
//!         let mut buffer = [0; 256];
//!         if let Ok(length) = tcp_stream.read(&mut buffer)
//!             && length != 0
//!         {
//!             let recevied_msg = &buffer[..length];
//!             assert_eq!(str::from_utf8(recevied_msg).unwrap(), "World");
//!         }
//!
//!         Ok::<(), Box<dyn Error>>(())
//!     })?;
//!
//!     Ok(())
//! }
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let zmq_stream = StreamSocket::from_context(&context)?;
//!     zmq_stream.bind("tcp://127.0.0.1:*")?;
//!     let tcp_endpoint = zmq_stream.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         let mut connect_msg = zmq_stream.recv_multipart(RecvFlags::empty()).unwrap();
//!         let routing_id = connect_msg.pop_front().unwrap();
//!
//!         loop {
//!             run_stream_socket(&zmq_stream, &routing_id.bytes(), "World").unwrap();
//!         }
//!     });
//!
//!     run_tcp_client(tcp_endpoint.strip_prefix("tcp://").unwrap(), iterations)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! [`Stream`]: StreamSocket
//!
//! ## Request-Reply pattern
//! The request-reply pattern is used for sending requests from a [`Request`] client to one or more
//! [`Reply`] services, and receiving subsequent replies to each request sent.
//!
//! ### Examples
//! Request-Reply sockets
//! ```
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, ReplySocket, RequestSocket, Sender, Receiver, SendFlags, RecvFlags};
//! #
//! pub fn run_recv_send<S>(recv_send: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Receiver + Sender,
//! {
//!     let message = recv_send.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "Hello");
//!
//!     recv_send.send_msg(msg, SendFlags::empty())
//! }
//!
//! pub fn run_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender + Receiver,
//! {
//!     send_recv.send_msg(msg, SendFlags::empty())?;
//!
//!     let message = send_recv.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let reply = ReplySocket::from_context(&context)?;
//!     reply.bind("tcp://127.0.0.1:*")?;
//!     let request_endpoint = reply.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         (1..=iterations)
//!             .try_for_each(|_| run_recv_send(&reply, "World"))
//!             .unwrap();
//!     });
//!
//!     let request = RequestSocket::from_context(&context)?;
//!     request.connect(request_endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_send_recv(&request, "Hello"))
//! }
//! ```
//!
//! Request-Router sockets
//! ```
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, RequestSocket, RouterSocket, Sender, Receiver, SendFlags, RecvFlags, MultipartSender, MultipartReceiver};
//! #
//! pub fn run_multipart_recv_reply<S>(recv_send: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: MultipartSender + MultipartReceiver,
//! {
//!     let mut multipart = recv_send.recv_multipart(RecvFlags::empty())?;
//!
//!     let content = multipart.pop_back().unwrap();
//!     if !content.is_empty() {
//!         assert_eq!(content.to_string(), "Hello");
//!     }
//!
//!     multipart.push_back(msg.into());
//!     recv_send.send_multipart(multipart, SendFlags::empty())
//! }
//!
//! pub fn run_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: Sender + Receiver,
//! {
//!     send_recv.send_msg(msg, SendFlags::empty())?;
//!
//!     let message = send_recv.recv_msg(RecvFlags::empty())?;
//!     assert_eq!(message.to_string(), "World");
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let router = RouterSocket::from_context(&context)?;
//!     router.bind("tcp://127.0.0.1:*")?;
//!     let request_endpoint = router.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         (0..iterations)
//!             .try_for_each(|_| run_multipart_recv_reply(&router, "World"))
//!             .unwrap();
//!     });
//!
//!     let request = RequestSocket::from_context(&context)?;
//!     request.connect(request_endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_send_recv(&request, "Hello"))
//! }
//! ```
//!
//! Dealer-Router sockets
//! ```
//! # use std::thread;
//! #
//! # use arzmq::prelude::{ZmqResult, Context, Message, DealerSocket, RouterSocket, MultipartReceiver, MultipartSender, SendFlags, RecvFlags};
//! #
//! pub fn run_multipart_recv_reply<S>(recv_send: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: MultipartSender + MultipartReceiver,
//! {
//!     let mut multipart = recv_send.recv_multipart(RecvFlags::empty())?;
//!
//!     let content = multipart.pop_back().unwrap();
//!     if !content.is_empty() {
//!         assert_eq!(content.to_string(), "Hello");
//!     }
//!
//!     multipart.push_back(msg.into());
//!     recv_send.send_multipart(multipart, SendFlags::empty())
//! }
//!
//! pub fn run_multipart_send_recv<S>(send_recv: &S, msg: &str) -> ZmqResult<()>
//! where
//!     S: MultipartReceiver + MultipartSender,
//! {
//!     println!("Sending message {msg:?}");
//!     let multipart: Vec<Message> = vec![vec![].into(), msg.into()];
//!     send_recv.send_multipart(multipart, SendFlags::empty())?;
//!
//!     let mut multipart = send_recv.recv_multipart(RecvFlags::empty())?;
//!     let content = multipart.pop_back().unwrap();
//!     if !content.is_empty() {
//!         assert_eq!(content.to_string(), "World");
//!     }
//!
//!     Ok(())
//! }
//!
//! fn main() -> ZmqResult<()> {
//!     let iterations = 10;
//!
//!     let context = Context::new()?;
//!
//!     let router = RouterSocket::from_context(&context)?;
//!     router.bind("tcp://127.0.0.1:*")?;
//!     let dealer_endpoint = router.last_endpoint()?;
//!
//!     thread::spawn(move || {
//!         (0..iterations)
//!             .try_for_each(|_| run_multipart_recv_reply(&router, "World"))
//!             .unwrap();
//!     });
//!
//!     let dealer = DealerSocket::from_context(&context)?;
//!     dealer.connect(dealer_endpoint)?;
//!
//!     (0..iterations).try_for_each(|_| run_multipart_send_recv(&dealer, "Hello"))
//! }
//! ```
//!
//! [`Request`]: RequestSocket
//! [`Reply`]: ReplySocket

use alloc::sync::Arc;
use core::{iter, marker::PhantomData, ops::ControlFlow};

#[cfg(feature = "futures")]
use ::futures::{FutureExt, TryStreamExt};
#[cfg(feature = "futures")]
use async_trait::async_trait;
use bitflags::bitflags;
use derive_more::From;
use num_traits::PrimInt;

use crate::{
    ZmqError, ZmqResult,
    context::Context,
    ffi::RawSocket,
    message::{Message, MultipartMessage, Sendable},
    sealed, zmq_sys_crate,
};

#[cfg(feature = "draft-api")]
mod channel;
#[cfg(feature = "draft-api")]
mod client;
mod dealer;
#[cfg(feature = "draft-api")]
mod dish;
#[cfg(feature = "draft-api")]
mod gather;
pub(crate) mod monitor;
mod pair;
#[cfg(feature = "draft-api")]
mod peer;
mod publish;
mod pull;
mod push;
#[cfg(feature = "draft-api")]
mod radio;
mod reply;
mod request;
mod router;
#[cfg(feature = "draft-api")]
mod scatter;
#[cfg(feature = "draft-api")]
mod server;
mod stream;
mod subscribe;
mod xpublish;
mod xsubscribe;

#[cfg(feature = "builder")]
pub use builder::SocketBuilder;
#[cfg(feature = "draft-api")]
pub use channel::ChannelSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use channel::builder::ChannelBuilder;
#[cfg(feature = "draft-api")]
pub use client::ClientSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use client::builder::ClientBuilder;
pub use dealer::DealerSocket;
#[cfg(feature = "builder")]
pub use dealer::builder::DealerBuilder;
#[cfg(feature = "draft-api")]
pub use dish::DishSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use dish::builder::DishBuilder;
#[cfg(feature = "draft-api")]
pub use gather::GatherSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use gather::builder::GatherBuilder;
use monitor::Monitor;
pub use monitor::{HandshakeProtocolError, MonitorReceiver, MonitorSocket, MonitorSocketEvent};
pub use pair::PairSocket;
#[cfg(feature = "builder")]
pub use pair::builder::PairBuilder;
#[cfg(feature = "draft-api")]
pub use peer::PeerSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use peer::builder::PeerBuilder;
pub use publish::PublishSocket;
#[cfg(feature = "builder")]
pub use publish::builder::PublishBuilder;
pub use pull::PullSocket;
#[cfg(feature = "builder")]
pub use pull::builder::PullBuilder;
pub use push::PushSocket;
#[cfg(feature = "builder")]
pub use push::builder::PushBuilder;
#[cfg(feature = "draft-api")]
pub use radio::RadioSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use radio::builder::RadioBuilder;
pub use reply::ReplySocket;
#[cfg(feature = "builder")]
pub use reply::builder::ReplyBuilder;
pub use request::RequestSocket;
#[cfg(feature = "builder")]
pub use request::builder::RequestBuilder;
#[cfg(feature = "draft-api")]
pub use router::RouterNotify;
pub use router::RouterSocket;
#[cfg(feature = "builder")]
pub use router::builder::RouterBuilder;
#[cfg(feature = "draft-api")]
pub use scatter::ScatterSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use scatter::builder::ScatterBuilder;
#[cfg(feature = "draft-api")]
pub use server::ServerSocket;
#[cfg(all(feature = "draft-api", feature = "builder"))]
pub use server::builder::ServerBuilder;
pub use stream::StreamSocket;
#[cfg(feature = "builder")]
pub use stream::builder::StreamBuilder;
pub use subscribe::SubscribeSocket;
#[cfg(feature = "builder")]
pub use subscribe::builder::SubscribeBuilder;
pub use xpublish::XPublishSocket;
#[cfg(feature = "builder")]
pub use xpublish::builder::XPublishBuilder;
#[doc(hidden)]
pub use xsubscribe::XSubscribeSocket;
#[cfg(feature = "builder")]
pub use xsubscribe::builder::XSubscribeBuilder;

#[cfg(zmq_has = "gssapi")]
use crate::security::GssApiNametype;
use crate::{auth::ZapDomain, security::SecurityMechanism};

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
/// Socket type
pub enum SocketType {
    /// [`PairSocket`]
    Pair,
    /// [`PublishSocket`]
    Publish,
    /// [`SubscribeSocket`]
    Subscribe,
    /// [`RequestSocket`]
    Request,
    /// [`ReplySocket`]
    Reply,
    /// [`DealerSocket`]
    Dealer,
    /// [`RouterSocket`]
    Router,
    /// [`PullSocket`]
    Pull,
    /// [`PushSocket`]
    Push,
    /// [`XPublishSocket`]
    XPublish,
    /// [`XSubscribeSocket`]
    XSubscribe,
    /// [`StreamSocket`]
    Stream,
    #[cfg(feature = "draft-api")]
    /// [`ServerSocket`]
    Server,
    #[cfg(feature = "draft-api")]
    /// [`ClientSocket`]
    Client,
    #[cfg(feature = "draft-api")]
    /// [`RadioSocket`]
    Radio,
    #[cfg(feature = "draft-api")]
    /// [`DishSocket`]
    Dish,
    #[cfg(feature = "draft-api")]
    /// [`GatherSocket`]
    Gather,
    #[cfg(feature = "draft-api")]
    /// [`ScatterSocket`]
    Scatter,
    #[cfg(feature = "draft-api")]
    /// DGRAM sockets
    Datagram,
    #[cfg(feature = "draft-api")]
    /// [`PeerSocket`]
    Peer,
    #[cfg(feature = "draft-api")]
    /// [`ChannelSocket`]
    Channel,
}

impl From<SocketType> for i32 {
    fn from(value: SocketType) -> Self {
        match value {
            SocketType::Pair => zmq_sys_crate::ZMQ_PAIR as i32,
            SocketType::Publish => zmq_sys_crate::ZMQ_PUB as i32,
            SocketType::Subscribe => zmq_sys_crate::ZMQ_SUB as i32,
            SocketType::Request => zmq_sys_crate::ZMQ_REQ as i32,
            SocketType::Reply => zmq_sys_crate::ZMQ_REP as i32,
            SocketType::Dealer => zmq_sys_crate::ZMQ_DEALER as i32,
            SocketType::Router => zmq_sys_crate::ZMQ_ROUTER as i32,
            SocketType::Pull => zmq_sys_crate::ZMQ_PULL as i32,
            SocketType::Push => zmq_sys_crate::ZMQ_PUSH as i32,
            SocketType::XPublish => zmq_sys_crate::ZMQ_XPUB as i32,
            SocketType::XSubscribe => zmq_sys_crate::ZMQ_XSUB as i32,
            SocketType::Stream => zmq_sys_crate::ZMQ_STREAM as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Server => zmq_sys_crate::ZMQ_SERVER as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Client => zmq_sys_crate::ZMQ_CLIENT as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Radio => zmq_sys_crate::ZMQ_RADIO as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Dish => zmq_sys_crate::ZMQ_DISH as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Gather => zmq_sys_crate::ZMQ_GATHER as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Scatter => zmq_sys_crate::ZMQ_SCATTER as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Datagram => zmq_sys_crate::ZMQ_DGRAM as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Peer => zmq_sys_crate::ZMQ_PEER as i32,
            #[cfg(feature = "draft-api")]
            SocketType::Channel => zmq_sys_crate::ZMQ_CHANNEL as i32,
        }
    }
}

#[cfg(test)]
mod socket_type_tests {
    use rstest::*;

    use super::SocketType;
    use crate::zmq_sys_crate;

    #[rstest]
    #[case(SocketType::Pair, zmq_sys_crate::ZMQ_PAIR as i32)]
    #[case(SocketType::Publish, zmq_sys_crate::ZMQ_PUB as i32)]
    #[case(SocketType::Subscribe, zmq_sys_crate::ZMQ_SUB as i32)]
    #[case(SocketType::Request, zmq_sys_crate::ZMQ_REQ as i32)]
    #[case(SocketType::Reply, zmq_sys_crate::ZMQ_REP as i32)]
    #[case(SocketType::Dealer, zmq_sys_crate::ZMQ_DEALER as i32)]
    #[case(SocketType::Router, zmq_sys_crate::ZMQ_ROUTER as i32)]
    #[case(SocketType::Pull, zmq_sys_crate::ZMQ_PULL as i32)]
    #[case(SocketType::Push, zmq_sys_crate::ZMQ_PUSH as i32)]
    #[case(SocketType::XPublish, zmq_sys_crate::ZMQ_XPUB as i32)]
    #[case(SocketType::XSubscribe, zmq_sys_crate::ZMQ_XSUB as i32)]
    #[case(SocketType::Stream, zmq_sys_crate::ZMQ_STREAM as i32)]
    #[cfg_attr(feature = "draft-api", case(SocketType::Server, zmq_sys_crate::ZMQ_SERVER as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Client, zmq_sys_crate::ZMQ_CLIENT as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Radio, zmq_sys_crate::ZMQ_RADIO as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Dish, zmq_sys_crate::ZMQ_DISH as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Gather, zmq_sys_crate::ZMQ_GATHER as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Scatter, zmq_sys_crate::ZMQ_SCATTER as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Datagram, zmq_sys_crate::ZMQ_DGRAM as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Peer, zmq_sys_crate::ZMQ_PEER as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketType::Channel, zmq_sys_crate::ZMQ_CHANNEL as i32))]
    fn converts_to_raw(#[case] socket_type: SocketType, #[case] raw: i32) {
        assert_eq!(<SocketType as Into<i32>>::into(socket_type), raw);
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
#[non_exhaustive]
/// Options that can be set or retrieved on a 0MQ socket
pub enum SocketOption {
    /// Socket type
    Type,

    /// I/O thread affinity
    Affinity,
    /// File descriptor associated with the socket
    FileDescriptor,
    /// Retrive the pre-allocated socket file descriptor
    UseFd,
    /// Name of the devive to bind the socket to
    BindToDevice,
    /// Type-of-service on the underlying socket
    TypeOfService,
    /// IPv6 setting
    IPv6,

    /// Connect timeout
    ConnectTimeout,
    #[cfg(feature = "draft-api")]
    /// Set a hello message that will be sent when a new peer connects
    HelloMessage,
    /// Maximum handshake interval
    HandshakeInterval,

    /// Last endpoint set
    LastEndpoint,

    /// Interval between sending ZMTP heartbeats
    HeartbeatInterval,
    /// Time-to-live for ZMTP heartbeats
    HeartbeatTimeToLive,
    /// Timeout for ZMTP heartbeats
    HeartbeatTimeout,

    /// Reconnection interval
    ReconnectInterval,
    /// Maximum reconnection interval
    ReconnectIntervalMax,
    #[cfg(feature = "draft-api")]
    /// Set a hiccup message that the socket will generate when connected peer temprarily
    /// disconnects
    HiccupMessage,
    #[cfg(feature = "draft-api")]
    /// Set condition when reconnection will stop
    ReconnectStop,

    #[cfg(feature = "draft-api")]
    /// Set a disconnect message that the socket will generate when accepted peer disconnect
    DisconnectMessage,

    /// Socket event state
    Events,
    /// Linger period for socket shutdown
    Linger,
    /// Queue messages only to completed connections
    Immediate,

    /// Keep only last message
    Conflate,
    /// more message data to follow
    ReceiveMore,
    /// Maximum length of the queue of outstanding connections
    Backlog,
    /// Maximum acceptable inbound message size
    MaxMessageSize,
    /// Kernel receive buffer size
    ReceiveBuffer,
    /// Maximum time before a socket operation returns with [`Again`](crate::ZmqError::Again)
    ReceiveTimeout,
    /// High water mark for inbound messages
    ReceiveHighWatermark,
    /// Kernel transmit buffer size
    SendBuffer,
    /// Maximum time before a socket operation returns with [`Again`](crate::ZmqError::Again)
    SendTimeout,
    /// High water mark for outbound messages
    SendHighWatermark,
    /// Retrieve socket thread-safety
    ThreadSafe,
    #[cfg(feature = "draft-api")]
    /// Application metadata properties on the socket
    Metadata,
    #[cfg(feature = "draft-api")]
    /// Maximum receive batch size
    InBatchSize,
    #[cfg(feature = "draft-api")]
    /// Maximum send batch size
    OutBatchSize,
    #[cfg(feature = "draft-api")]
    /// Set the priority on the socket
    Priority,
    #[cfg(feature = "draft-api")]
    /// This removes delays caused by the interrupt and the resultant context switch
    BusyPoll,

    /// Socket routing id
    RoutingId,
    /// Accept only routable messages on [`Router`](RouterSocket) sockets
    RouterMandatory,
    /// Handle duplicate client routing ids on [`Router`](RouterSocket) sockets
    RouterHandover,
    /// Bootstrap connections to [`Router`](RouterSocket) sockets
    ProbeRouter,
    /// Next outbound routing id
    ConnectRoutingId,
    #[cfg(feature = "draft-api")]
    /// Send connect and disconnect notifications
    RouterNotify,

    /// Match replies with requests on [`Request`](RequestSocket) sockets
    RequestCorrelate,
    /// Relax strict alternation between reques and reply
    RequestRelaxed,

    /// Establish message filter
    Subscribe,
    /// Remove message filter
    Unsubscribe,
    /// Invert message filtering
    InvertMatching,
    #[cfg(feature = "draft-api")]
    /// Process only first subscribe/unsubscribe in a multipart message
    OnlyFirstSubscribe,
    #[cfg(feature = "draft-api")]
    /// Pass duplicate unsubscribe messages on [`XSubscribe`](XSubscribeSocket) sockets
    XsubVerboseUnsubscribe,
    #[cfg(feature = "draft-api")]
    /// Number of topic subscriptions received
    TopicsCount,

    /// Pass duplicate subscribe messages on [`XPublish`](XPublishSocket) sockets
    XpubVerbose,
    /// Pass duplicate subscribe and unsubscribe message on [`XPublish`](XPublishSocket) sockets
    XpubVerboser,
    /// Do not silently drop message if SendHighWatermark is reached on [`XPublish`](XPublishSocket)
    /// sockets
    XpubNoDrop,
    /// Change the subscription handling to manual
    XpubManual,
    /// Welcome message that will be received by [`Subscribe`](SubscribeSocket) when connecting to a
    /// [`XPublish`](XPublishSocket) socket.
    XpubWelcomeMessage,
    #[cfg(feature = "draft-api")]
    /// Change the subscription handling to manual
    XpubManualLastValue,

    /// Send connect and disconnect notifications
    StreamNotify,

    /// Multicast data rate
    Rate,
    /// Multicast recovery interval
    RecoveryInterval,
    /// Maximum network hops for multicast packets
    MulticastHops,
    /// Maximum transport data unit size for multicast packets
    MulticastMaxTransportDataUnitSize,
    #[cfg(feature = "draft-api")]
    /// Control multicast local loopback
    MulticastLoop,

    /// Overrides SO_KEEPALIVE socket option
    TcpKeepalive,
    /// Override TCP_KEEPCNT sockt option
    TcpKeepaliveCount,
    /// Override TCP_KEEPIDLE sockt option
    TcpKeepaliveIdle,
    /// Override TCP_KEEPINTVL sockt option
    TcpKeepaliveInterval,
    /// Assign filters to allow new TCP connections
    TcpAcceptFilter,
    /// TCP maximum retransmit timeout
    MaxTcpRetransmitTimeout,

    #[cfg(zmq_has = "ipc")]
    /// Process ID filters to allow new IPC connections
    IpcFilterProcessId,
    #[cfg(zmq_has = "ipc")]
    /// User ID filters to allow new IPC connections
    IpcFilterUserId,
    #[cfg(zmq_has = "ipc")]
    /// Group ID filters to allow new IPC connections
    IpcFilterGroupId,

    #[cfg(zmq_has = "vmci")]
    /// Buffer size of the VMCI socket
    VmciBufferSize,
    #[cfg(zmq_has = "vmci")]
    /// Minimum buffer size of the VMCI socket
    VmciBufferMinSize,
    #[cfg(zmq_has = "vmci")]
    /// Maximum buffer size of the VMCI socket
    VmciBufferMaxSize,
    #[cfg(zmq_has = "vmci")]
    /// Connection timeout of the VMCI socket
    VmciConntectTimeout,

    #[cfg(zmq_has = "norm")]
    /// NORM sender mode
    NormMode,
    #[cfg(zmq_has = "norm")]
    /// NORM unicast NACK mode
    NormUnicastNack,
    #[cfg(zmq_has = "norm")]
    /// NORM buffer size
    NormBufferSize,
    #[cfg(zmq_has = "norm")]
    /// NORM segment size
    NormSegmentSize,
    #[cfg(zmq_has = "norm")]
    /// NORM block size
    NormBlockSize,
    #[cfg(zmq_has = "norm")]
    /// NORM parity segment setting
    NormNumnParity,
    #[cfg(zmq_has = "norm")]
    /// Proactive NORM parity segment setting
    NormNumnAutoParity,
    #[cfg(zmq_has = "norm")]
    /// NORM push mode
    NormPush,

    /// RFC27 authentifcation domain
    ZapDomain,
    #[cfg(feature = "draft-api")]
    /// Strict ZAP domain handling
    ZapEnforceDomain,

    /// SOCKS5 proxy address
    SocksProxy,
    #[cfg(feature = "draft-api")]
    /// SOCKS username and select basic authentification
    SocksUsername,
    #[cfg(feature = "draft-api")]
    /// SOCKS basic authentification password
    SocksPassword,

    /// Current security mechanism
    Mechanism,
    /// Current PLAIN server role
    PlainServer,
    /// Current PLAIN username
    PlainUsername,
    /// Current PLAIN password
    PlainPassword,
    #[cfg(zmq_has = "curve")]
    /// Current CURVE public key
    CurvePublicKey,
    #[cfg(zmq_has = "curve")]
    /// Current CURVE secret key
    CurveSecretKey,
    #[cfg(zmq_has = "curve")]
    /// Current CURVE server role
    CurveServer,
    #[cfg(zmq_has = "curve")]
    /// Current CURVE server key
    CurveServerKey,
    #[cfg(zmq_has = "gssapi")]
    /// GSSAPI server role
    GssApiServer,
    #[cfg(zmq_has = "gssapi")]
    /// Name of GSSAPI principal
    GssApiPrincipal,
    #[cfg(zmq_has = "gssapi")]
    /// Name of GSSAPI service principal
    GssApiServicePrincipal,
    #[cfg(zmq_has = "gssapi")]
    /// Enable/disable GSSAPI encryption
    GssApiPlainText,
    #[cfg(zmq_has = "gssapi")]
    /// Nametype for GSSAPI principal
    GssApiPrincipalNametype,
    #[cfg(zmq_has = "gssapi")]
    /// Nametype for GSSAPI service principal
    GssApiServicePrincipalNametype,
}

impl From<SocketOption> for i32 {
    fn from(value: SocketOption) -> Self {
        match value {
            SocketOption::Affinity => zmq_sys_crate::ZMQ_AFFINITY as i32,
            SocketOption::RoutingId => zmq_sys_crate::ZMQ_ROUTING_ID as i32,
            SocketOption::Subscribe => zmq_sys_crate::ZMQ_SUBSCRIBE as i32,
            SocketOption::Unsubscribe => zmq_sys_crate::ZMQ_UNSUBSCRIBE as i32,
            SocketOption::Rate => zmq_sys_crate::ZMQ_RATE as i32,
            SocketOption::RecoveryInterval => zmq_sys_crate::ZMQ_RECOVERY_IVL as i32,
            SocketOption::SendBuffer => zmq_sys_crate::ZMQ_SNDBUF as i32,
            SocketOption::ReceiveBuffer => zmq_sys_crate::ZMQ_RCVBUF as i32,
            SocketOption::ReceiveMore => zmq_sys_crate::ZMQ_RCVMORE as i32,
            SocketOption::FileDescriptor => zmq_sys_crate::ZMQ_FD as i32,
            SocketOption::Events => zmq_sys_crate::ZMQ_EVENTS as i32,
            SocketOption::Type => zmq_sys_crate::ZMQ_TYPE as i32,
            SocketOption::Linger => zmq_sys_crate::ZMQ_LINGER as i32,
            SocketOption::ReconnectInterval => zmq_sys_crate::ZMQ_RECONNECT_IVL as i32,
            SocketOption::Backlog => zmq_sys_crate::ZMQ_BACKLOG as i32,
            SocketOption::ReconnectIntervalMax => zmq_sys_crate::ZMQ_RECONNECT_IVL_MAX as i32,
            SocketOption::MaxMessageSize => zmq_sys_crate::ZMQ_MAXMSGSIZE as i32,
            SocketOption::SendHighWatermark => zmq_sys_crate::ZMQ_SNDHWM as i32,
            SocketOption::ReceiveHighWatermark => zmq_sys_crate::ZMQ_RCVHWM as i32,
            SocketOption::MulticastHops => zmq_sys_crate::ZMQ_MULTICAST_HOPS as i32,
            SocketOption::ReceiveTimeout => zmq_sys_crate::ZMQ_RCVTIMEO as i32,
            SocketOption::SendTimeout => zmq_sys_crate::ZMQ_SNDTIMEO as i32,
            SocketOption::LastEndpoint => zmq_sys_crate::ZMQ_LAST_ENDPOINT as i32,
            SocketOption::RouterMandatory => zmq_sys_crate::ZMQ_ROUTER_MANDATORY as i32,
            SocketOption::TcpKeepalive => zmq_sys_crate::ZMQ_TCP_KEEPALIVE as i32,
            SocketOption::TcpKeepaliveCount => zmq_sys_crate::ZMQ_TCP_KEEPALIVE_CNT as i32,
            SocketOption::TcpKeepaliveIdle => zmq_sys_crate::ZMQ_TCP_KEEPALIVE_IDLE as i32,
            SocketOption::TcpKeepaliveInterval => zmq_sys_crate::ZMQ_TCP_KEEPALIVE_INTVL as i32,
            SocketOption::TcpAcceptFilter => zmq_sys_crate::ZMQ_TCP_ACCEPT_FILTER as i32,
            SocketOption::Immediate => zmq_sys_crate::ZMQ_IMMEDIATE as i32,
            SocketOption::XpubVerbose => zmq_sys_crate::ZMQ_XPUB_VERBOSE as i32,
            SocketOption::IPv6 => zmq_sys_crate::ZMQ_IPV6 as i32,
            SocketOption::Mechanism => zmq_sys_crate::ZMQ_MECHANISM as i32,
            SocketOption::PlainServer => zmq_sys_crate::ZMQ_PLAIN_SERVER as i32,
            SocketOption::PlainUsername => zmq_sys_crate::ZMQ_PLAIN_USERNAME as i32,
            SocketOption::PlainPassword => zmq_sys_crate::ZMQ_PLAIN_PASSWORD as i32,
            #[cfg(zmq_has = "curve")]
            SocketOption::CurvePublicKey => zmq_sys_crate::ZMQ_CURVE_PUBLICKEY as i32,
            #[cfg(zmq_has = "curve")]
            SocketOption::CurveSecretKey => zmq_sys_crate::ZMQ_CURVE_SECRETKEY as i32,
            #[cfg(zmq_has = "curve")]
            SocketOption::CurveServer => zmq_sys_crate::ZMQ_CURVE_SERVER as i32,
            #[cfg(zmq_has = "curve")]
            SocketOption::CurveServerKey => zmq_sys_crate::ZMQ_CURVE_SERVERKEY as i32,
            SocketOption::ProbeRouter => zmq_sys_crate::ZMQ_PROBE_ROUTER as i32,
            SocketOption::RequestCorrelate => zmq_sys_crate::ZMQ_REQ_CORRELATE as i32,
            SocketOption::RequestRelaxed => zmq_sys_crate::ZMQ_REQ_RELAXED as i32,
            SocketOption::Conflate => zmq_sys_crate::ZMQ_CONFLATE as i32,
            SocketOption::ZapDomain => zmq_sys_crate::ZMQ_ZAP_DOMAIN as i32,
            SocketOption::RouterHandover => zmq_sys_crate::ZMQ_ROUTER_HANDOVER as i32,
            SocketOption::TypeOfService => zmq_sys_crate::ZMQ_TOS as i32,
            SocketOption::IpcFilterProcessId => zmq_sys_crate::ZMQ_IPC_FILTER_PID as i32,
            SocketOption::IpcFilterUserId => zmq_sys_crate::ZMQ_IPC_FILTER_UID as i32,
            SocketOption::IpcFilterGroupId => zmq_sys_crate::ZMQ_IPC_FILTER_GID as i32,
            SocketOption::ConnectRoutingId => zmq_sys_crate::ZMQ_CONNECT_ROUTING_ID as i32,
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiServer => zmq_sys_crate::ZMQ_GSSAPI_SERVER as i32,
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiPrincipal => zmq_sys_crate::ZMQ_GSSAPI_PRINCIPAL as i32,
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiServicePrincipal => {
                zmq_sys_crate::ZMQ_GSSAPI_SERVICE_PRINCIPAL as i32
            }
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiPlainText => zmq_sys_crate::ZMQ_GSSAPI_PLAINTEXT as i32,
            SocketOption::HandshakeInterval => zmq_sys_crate::ZMQ_HANDSHAKE_IVL as i32,
            SocketOption::SocksProxy => zmq_sys_crate::ZMQ_SOCKS_PROXY as i32,
            SocketOption::XpubNoDrop => zmq_sys_crate::ZMQ_XPUB_NODROP as i32,
            SocketOption::XpubManual => zmq_sys_crate::ZMQ_XPUB_MANUAL as i32,
            SocketOption::XpubWelcomeMessage => zmq_sys_crate::ZMQ_XPUB_WELCOME_MSG as i32,
            SocketOption::StreamNotify => zmq_sys_crate::ZMQ_STREAM_NOTIFY as i32,
            SocketOption::InvertMatching => zmq_sys_crate::ZMQ_INVERT_MATCHING as i32,
            SocketOption::HeartbeatInterval => zmq_sys_crate::ZMQ_HEARTBEAT_IVL as i32,
            SocketOption::HeartbeatTimeToLive => zmq_sys_crate::ZMQ_HEARTBEAT_TTL as i32,
            SocketOption::HeartbeatTimeout => zmq_sys_crate::ZMQ_HEARTBEAT_TIMEOUT as i32,
            SocketOption::XpubVerboser => zmq_sys_crate::ZMQ_XPUB_VERBOSER as i32,
            SocketOption::ConnectTimeout => zmq_sys_crate::ZMQ_CONNECT_TIMEOUT as i32,
            SocketOption::MaxTcpRetransmitTimeout => zmq_sys_crate::ZMQ_TCP_MAXRT as i32,
            SocketOption::MulticastMaxTransportDataUnitSize => {
                zmq_sys_crate::ZMQ_MULTICAST_MAXTPDU as i32
            }
            SocketOption::ThreadSafe => zmq_sys_crate::ZMQ_THREAD_SAFE as i32,
            #[cfg(zmq_has = "vmci")]
            SocketOption::VmciBufferSize => zmq_sys_crate::ZMQ_VMCI_BUFFER_SIZE as i32,
            #[cfg(zmq_has = "vmci")]
            SocketOption::VmciBufferMinSize => zmq_sys_crate::ZMQ_VMCI_BUFFER_MIN_SIZE as i32,
            #[cfg(zmq_has = "vmci")]
            SocketOption::VmciBufferMaxSize => zmq_sys_crate::ZMQ_VMCI_BUFFER_MAX_SIZE as i32,
            #[cfg(zmq_has = "vmci")]
            SocketOption::VmciConntectTimeout => zmq_sys_crate::ZMQ_VMCI_CONNECT_TIMEOUT as i32,
            SocketOption::UseFd => zmq_sys_crate::ZMQ_USE_FD as i32,
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiPrincipalNametype => {
                zmq_sys_crate::ZMQ_GSSAPI_PRINCIPAL_NAMETYPE as i32
            }
            #[cfg(zmq_has = "gssapi")]
            SocketOption::GssApiServicePrincipalNametype => {
                zmq_sys_crate::ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE as i32
            }
            SocketOption::BindToDevice => zmq_sys_crate::ZMQ_BINDTODEVICE as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::ZapEnforceDomain => zmq_sys_crate::ZMQ_ZAP_ENFORCE_DOMAIN as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::Metadata => zmq_sys_crate::ZMQ_METADATA as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::MulticastLoop => zmq_sys_crate::ZMQ_MULTICAST_LOOP as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::RouterNotify => zmq_sys_crate::ZMQ_ROUTER_NOTIFY as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::XpubManualLastValue => zmq_sys_crate::ZMQ_XPUB_MANUAL_LAST_VALUE as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::SocksUsername => zmq_sys_crate::ZMQ_SOCKS_USERNAME as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::SocksPassword => zmq_sys_crate::ZMQ_SOCKS_PASSWORD as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::InBatchSize => zmq_sys_crate::ZMQ_IN_BATCH_SIZE as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::OutBatchSize => zmq_sys_crate::ZMQ_OUT_BATCH_SIZE as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::OnlyFirstSubscribe => zmq_sys_crate::ZMQ_ONLY_FIRST_SUBSCRIBE as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::ReconnectStop => zmq_sys_crate::ZMQ_RECONNECT_STOP as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::HelloMessage => zmq_sys_crate::ZMQ_HELLO_MSG as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::DisconnectMessage => zmq_sys_crate::ZMQ_DISCONNECT_MSG as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::Priority => zmq_sys_crate::ZMQ_PRIORITY as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::BusyPoll => zmq_sys_crate::ZMQ_BUSY_POLL as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::HiccupMessage => zmq_sys_crate::ZMQ_HICCUP_MSG as i32,
            #[cfg(feature = "draft-api")]
            SocketOption::XsubVerboseUnsubscribe => {
                zmq_sys_crate::ZMQ_XSUB_VERBOSE_UNSUBSCRIBE as i32
            }
            #[cfg(feature = "draft-api")]
            SocketOption::TopicsCount => zmq_sys_crate::ZMQ_TOPICS_COUNT as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormMode => zmq_sys_crate::ZMQ_NORM_MODE as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormUnicastNack => zmq_sys_crate::ZMQ_NORM_UNICAST_NACK as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormBufferSize => zmq_sys_crate::ZMQ_NORM_BUFFER_SIZE as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormSegmentSize => zmq_sys_crate::ZMQ_NORM_SEGMENT_SIZE as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormBlockSize => zmq_sys_crate::ZMQ_NORM_BLOCK_SIZE as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormNumnParity => zmq_sys_crate::ZMQ_NORM_NUM_PARITY as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormNumnAutoParity => zmq_sys_crate::ZMQ_NORM_NUM_AUTOPARITY as i32,
            #[cfg(zmq_has = "norm")]
            SocketOption::NormPush => zmq_sys_crate::ZMQ_NORM_PUSH as i32,
        }
    }
}

#[cfg(test)]
mod socket_option_tests {
    use rstest::*;

    use super::SocketOption;
    use crate::zmq_sys_crate;

    #[rstest]
    #[case(SocketOption::Affinity, zmq_sys_crate::ZMQ_AFFINITY as i32)]
    #[case(SocketOption::RoutingId, zmq_sys_crate::ZMQ_ROUTING_ID as i32)]
    #[case(SocketOption::Subscribe, zmq_sys_crate::ZMQ_SUBSCRIBE as i32)]
    #[case(SocketOption::Unsubscribe, zmq_sys_crate::ZMQ_UNSUBSCRIBE as i32)]
    #[case(SocketOption::Rate, zmq_sys_crate::ZMQ_RATE as i32)]
    #[case(SocketOption::RecoveryInterval, zmq_sys_crate::ZMQ_RECOVERY_IVL as i32)]
    #[case(SocketOption::SendBuffer, zmq_sys_crate::ZMQ_SNDBUF as i32)]
    #[case(SocketOption::ReceiveBuffer, zmq_sys_crate::ZMQ_RCVBUF as i32)]
    #[case(SocketOption::ReceiveMore, zmq_sys_crate::ZMQ_RCVMORE as i32)]
    #[case(SocketOption::FileDescriptor, zmq_sys_crate::ZMQ_FD as i32)]
    #[case(SocketOption::Events, zmq_sys_crate::ZMQ_EVENTS as i32)]
    #[case(SocketOption::Type, zmq_sys_crate::ZMQ_TYPE as i32)]
    #[case(SocketOption::Linger, zmq_sys_crate::ZMQ_LINGER as i32)]
    #[case(SocketOption::ReconnectInterval, zmq_sys_crate::ZMQ_RECONNECT_IVL as i32)]
    #[case(SocketOption::Backlog, zmq_sys_crate::ZMQ_BACKLOG as i32)]
    #[case(SocketOption::ReconnectIntervalMax, zmq_sys_crate::ZMQ_RECONNECT_IVL_MAX as i32)]
    #[case(SocketOption::MaxMessageSize, zmq_sys_crate::ZMQ_MAXMSGSIZE as i32)]
    #[case(SocketOption::SendHighWatermark, zmq_sys_crate::ZMQ_SNDHWM as i32)]
    #[case(SocketOption::ReceiveHighWatermark, zmq_sys_crate::ZMQ_RCVHWM as i32)]
    #[case(SocketOption::MulticastHops, zmq_sys_crate::ZMQ_MULTICAST_HOPS as i32)]
    #[case(SocketOption::ReceiveTimeout, zmq_sys_crate::ZMQ_RCVTIMEO as i32)]
    #[case(SocketOption::SendTimeout, zmq_sys_crate::ZMQ_SNDTIMEO as i32)]
    #[case(SocketOption::LastEndpoint, zmq_sys_crate::ZMQ_LAST_ENDPOINT as i32)]
    #[case(SocketOption::RouterMandatory, zmq_sys_crate::ZMQ_ROUTER_MANDATORY as i32)]
    #[case(SocketOption::TcpKeepalive, zmq_sys_crate::ZMQ_TCP_KEEPALIVE as i32)]
    #[case(SocketOption::TcpKeepaliveCount, zmq_sys_crate::ZMQ_TCP_KEEPALIVE_CNT as i32)]
    #[case(SocketOption::TcpKeepaliveIdle, zmq_sys_crate::ZMQ_TCP_KEEPALIVE_IDLE as i32)]
    #[case(SocketOption::TcpKeepaliveInterval, zmq_sys_crate::ZMQ_TCP_KEEPALIVE_INTVL as i32)]
    #[case(SocketOption::TcpAcceptFilter, zmq_sys_crate::ZMQ_TCP_ACCEPT_FILTER as i32)]
    #[case(SocketOption::Immediate, zmq_sys_crate::ZMQ_IMMEDIATE as i32)]
    #[case(SocketOption::XpubVerbose, zmq_sys_crate::ZMQ_XPUB_VERBOSE as i32)]
    #[case(SocketOption::IPv6, zmq_sys_crate::ZMQ_IPV6 as i32)]
    #[case(SocketOption::Mechanism, zmq_sys_crate::ZMQ_MECHANISM as i32)]
    #[case(SocketOption::PlainServer, zmq_sys_crate::ZMQ_PLAIN_SERVER as i32)]
    #[case(SocketOption::PlainUsername, zmq_sys_crate::ZMQ_PLAIN_USERNAME as i32)]
    #[case(SocketOption::PlainPassword, zmq_sys_crate::ZMQ_PLAIN_PASSWORD as i32)]
    #[cfg_attr(zmq_has = "curve", case(SocketOption::CurvePublicKey, zmq_sys_crate::ZMQ_CURVE_PUBLICKEY as i32))]
    #[cfg_attr(zmq_has = "curve", case(SocketOption::CurveSecretKey, zmq_sys_crate::ZMQ_CURVE_SECRETKEY as i32))]
    #[cfg_attr(zmq_has = "curve", case(SocketOption::CurveServer, zmq_sys_crate::ZMQ_CURVE_SERVER as i32))]
    #[cfg_attr(zmq_has = "curve", case(SocketOption::CurveServerKey, zmq_sys_crate::ZMQ_CURVE_SERVERKEY as i32))]
    #[case(SocketOption::ProbeRouter, zmq_sys_crate::ZMQ_PROBE_ROUTER as i32)]
    #[case(SocketOption::RequestCorrelate, zmq_sys_crate::ZMQ_REQ_CORRELATE as i32)]
    #[case(SocketOption::RequestRelaxed, zmq_sys_crate::ZMQ_REQ_RELAXED as i32)]
    #[case(SocketOption::Conflate, zmq_sys_crate::ZMQ_CONFLATE as i32)]
    #[case(SocketOption::ZapDomain, zmq_sys_crate::ZMQ_ZAP_DOMAIN as i32)]
    #[case(SocketOption::RouterHandover, zmq_sys_crate::ZMQ_ROUTER_HANDOVER as i32)]
    #[case(SocketOption::TypeOfService, zmq_sys_crate::ZMQ_TOS as i32)]
    #[case(SocketOption::IpcFilterProcessId, zmq_sys_crate::ZMQ_IPC_FILTER_PID as i32)]
    #[case(SocketOption::IpcFilterUserId, zmq_sys_crate::ZMQ_IPC_FILTER_UID as i32)]
    #[case(SocketOption::IpcFilterGroupId, zmq_sys_crate::ZMQ_IPC_FILTER_GID as i32)]
    #[case(SocketOption::ConnectRoutingId, zmq_sys_crate::ZMQ_CONNECT_ROUTING_ID as i32)]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiServer, zmq_sys_crate::ZMQ_GSSAPI_SERVER as i32))]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiPrincipal, zmq_sys_crate::ZMQ_GSSAPI_PRINCIPAL as i32))]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiServicePrincipal, zmq_sys_crate::ZMQ_GSSAPI_SERVICE_PRINCIPAL as i32))]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiPlainText, zmq_sys_crate::ZMQ_GSSAPI_PLAINTEXT as i32))]
    #[case(SocketOption::HandshakeInterval, zmq_sys_crate::ZMQ_HANDSHAKE_IVL as i32)]
    #[case(SocketOption::SocksProxy, zmq_sys_crate::ZMQ_SOCKS_PROXY as i32)]
    #[case(SocketOption::XpubNoDrop, zmq_sys_crate::ZMQ_XPUB_NODROP as i32)]
    #[case(SocketOption::XpubManual, zmq_sys_crate::ZMQ_XPUB_MANUAL as i32)]
    #[case(SocketOption::XpubWelcomeMessage, zmq_sys_crate::ZMQ_XPUB_WELCOME_MSG as i32)]
    #[case(SocketOption::StreamNotify, zmq_sys_crate::ZMQ_STREAM_NOTIFY as i32)]
    #[case(SocketOption::InvertMatching, zmq_sys_crate::ZMQ_INVERT_MATCHING as i32)]
    #[case(SocketOption::HeartbeatInterval, zmq_sys_crate::ZMQ_HEARTBEAT_IVL as i32)]
    #[case(SocketOption::HeartbeatTimeToLive, zmq_sys_crate::ZMQ_HEARTBEAT_TTL as i32)]
    #[case(SocketOption::HeartbeatTimeout, zmq_sys_crate::ZMQ_HEARTBEAT_TIMEOUT as i32)]
    #[case(SocketOption::XpubVerboser, zmq_sys_crate::ZMQ_XPUB_VERBOSER as i32)]
    #[case(SocketOption::ConnectTimeout, zmq_sys_crate::ZMQ_CONNECT_TIMEOUT as i32)]
    #[case(SocketOption::MaxTcpRetransmitTimeout, zmq_sys_crate::ZMQ_TCP_MAXRT as i32)]
    #[case(SocketOption::MulticastMaxTransportDataUnitSize, zmq_sys_crate::ZMQ_MULTICAST_MAXTPDU as i32)]
    #[case(SocketOption::ThreadSafe, zmq_sys_crate::ZMQ_THREAD_SAFE as i32)]
    #[cfg_attr(zmq_has = "vmci", case(SocketOption::VmciBufferSize, zmq_sys_crate::ZMQ_VMCI_BUFFER_SIZE as i32))]
    #[cfg_attr(zmq_has = "vmci", case(SocketOption::VmciBufferMinSize, zmq_sys_crate::ZMQ_VMCI_BUFFER_MIN_SIZE as i32))]
    #[cfg_attr(zmq_has = "vmci", case(SocketOption::VmciBufferMaxSize, zmq_sys_crate::ZMQ_VMCI_BUFFER_MAX_SIZE as i32))]
    #[cfg_attr(zmq_has = "vmci", case(SocketOption::VmciConntectTimeout, zmq_sys_crate::ZMQ_VMCI_CONNECT_TIMEOUT as i32))]
    #[case(SocketOption::UseFd, zmq_sys_crate::ZMQ_USE_FD as i32)]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiPrincipalNametype, zmq_sys_crate::ZMQ_GSSAPI_PRINCIPAL_NAMETYPE as i32))]
    #[cfg_attr(zmq_has = "gssapi", case(SocketOption::GssApiServicePrincipalNametype, zmq_sys_crate::ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE as i32))]
    #[case(SocketOption::BindToDevice, zmq_sys_crate::ZMQ_BINDTODEVICE as i32)]
    #[cfg_attr(feature = "draft-api", case(SocketOption::ZapEnforceDomain, zmq_sys_crate::ZMQ_ZAP_ENFORCE_DOMAIN as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::Metadata, zmq_sys_crate::ZMQ_METADATA as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::MulticastLoop, zmq_sys_crate::ZMQ_MULTICAST_LOOP as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::RouterNotify, zmq_sys_crate::ZMQ_ROUTER_NOTIFY as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::XpubManualLastValue, zmq_sys_crate::ZMQ_XPUB_MANUAL_LAST_VALUE as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::SocksUsername, zmq_sys_crate::ZMQ_SOCKS_USERNAME as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::SocksPassword, zmq_sys_crate::ZMQ_SOCKS_PASSWORD as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::InBatchSize, zmq_sys_crate::ZMQ_IN_BATCH_SIZE as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::OutBatchSize, zmq_sys_crate::ZMQ_OUT_BATCH_SIZE as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::OnlyFirstSubscribe, zmq_sys_crate::ZMQ_ONLY_FIRST_SUBSCRIBE as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::ReconnectStop, zmq_sys_crate::ZMQ_RECONNECT_STOP as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::HelloMessage, zmq_sys_crate::ZMQ_HELLO_MSG as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::DisconnectMessage, zmq_sys_crate::ZMQ_DISCONNECT_MSG as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::Priority, zmq_sys_crate::ZMQ_PRIORITY as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::BusyPoll, zmq_sys_crate::ZMQ_BUSY_POLL as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::HiccupMessage, zmq_sys_crate::ZMQ_HICCUP_MSG as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::XsubVerboseUnsubscribe, zmq_sys_crate::ZMQ_XSUB_VERBOSE_UNSUBSCRIBE as i32))]
    #[cfg_attr(feature = "draft-api", case(SocketOption::TopicsCount, zmq_sys_crate::ZMQ_TOPICS_COUNT as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormMode, zmq_sys_crate::ZMQ_NORM_MODE as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormUnicastNack, zmq_sys_crate::ZMQ_NORM_UNICAST_NACK as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormBufferSize, zmq_sys_crate::ZMQ_NORM_BUFFER_SIZE as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormSegmentSize, zmq_sys_crate::ZMQ_NORM_SEGMENT_SIZE as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormBlockSize, zmq_sys_crate::ZMQ_NORM_BLOCK_SIZE as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormNumnParity, zmq_sys_crate::ZMQ_NORM_NUM_PARITY as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormNumnAutoParity, zmq_sys_crate::ZMQ_NORM_NUM_AUTOPARITY as i32))]
    #[cfg_attr(zmq_has = "norm", case(SocketOption::NormPush, zmq_sys_crate::ZMQ_NORM_PUSH as i32))]
    fn converts_to_raw(#[case] option: SocketOption, #[case] expected: i32) {
        assert_eq!(<SocketOption as Into<i32>>::into(option), expected);
    }
}

/// generic 0MQ socket
pub struct Socket<T: sealed::SocketType> {
    context: Context,
    pub(crate) socket: Arc<RawSocket>,
    marker: PhantomData<T>,
}

impl<T: sealed::SocketType> Socket<T> {
    /// General constructor
    pub fn from_context(context: &Context) -> ZmqResult<Self> {
        let socket = RawSocket::from_ctx(&context.inner, T::raw_socket_type() as i32)?;
        Ok(Self {
            context: context.clone(),
            socket: socket.into(),
            marker: PhantomData,
        })
    }

    /// # set 0MQ socket options
    ///
    /// Sets a [`SocketOption`] option on the socket. The bytes version is mostly suitable for
    /// binary data options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn set_sockopt_bytes<V>(&self, option: SocketOption, value: V) -> ZmqResult<()>
    where
        V: AsRef<[u8]>,
    {
        self.socket.set_sockopt_bytes(option.into(), value.as_ref())
    }

    /// # set 0MQ socket options
    ///
    /// Sets a [`SocketOption`] option on the socket. The string version is mostly suitable for
    /// character string options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn set_sockopt_string<V>(&self, option: SocketOption, value: V) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        self.socket
            .set_sockopt_string(option.into(), value.as_ref())
    }

    /// # set 0MQ socket options
    ///
    /// Sets a [`SocketOption`] option on the socket. The int version is mostly suitable for
    /// integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn set_sockopt_int<V>(&self, option: SocketOption, value: V) -> ZmqResult<()>
    where
        V: PrimInt,
    {
        self.socket.set_sockopt_int(option.into(), value)
    }

    /// # set 0MQ socket options
    ///
    /// Sets a [`SocketOption`] option on the socket. The bool version is mostly suitable for
    /// 0/1 integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn set_sockopt_bool(&self, option: SocketOption, value: bool) -> ZmqResult<()> {
        self.socket.set_sockopt_bool(option.into(), value)
    }

    #[cfg(zmq_has = "curve")]
    pub(crate) fn get_sockopt_curve(&self, option: SocketOption) -> ZmqResult<Vec<u8>> {
        self.socket.get_sockopt_curve(option.into())
    }

    /// # get 0MQ socket options
    ///
    /// Gets a [`SocketOption`] option on the socket. The bytes version is mostly suitable for
    /// binary data options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn get_sockopt_bytes(&self, option: SocketOption) -> ZmqResult<Vec<u8>> {
        self.socket.get_sockopt_bytes(option.into())
    }

    /// # get 0MQ socket options
    ///
    /// Gets a [`SocketOption`] option on the socket. The string version is mostly suitable for
    /// character string options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn get_sockopt_string(&self, option: SocketOption) -> ZmqResult<String> {
        self.socket.get_sockopt_string(option.into())
    }

    /// # get 0MQ socket options
    ///
    /// Gets a [`SocketOption`] option on the socket. The int version is mostly suitable for
    /// integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn get_sockopt_int<V>(&self, option: SocketOption) -> ZmqResult<V>
    where
        V: PrimInt + Default,
    {
        self.socket.get_sockopt_int(option.into())
    }

    /// # get 0MQ socket options
    ///
    /// Gets a [`SocketOption`] option on the socket. The bool version is mostly suitable for
    /// 0/1 integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`SocketOption`]: SocketOption
    pub fn get_sockopt_bool(&self, option: SocketOption) -> ZmqResult<bool> {
        self.socket.get_sockopt_bool(option.into())
    }

    /// # Set I/O thread affinity `ZMQ_AFFINITY`
    ///
    /// The [`Affinity`] option shall set the I/O thread affinity for newly created connections on
    /// the specified [`Socket`].
    ///
    /// Affinity determines which threads from the 0MQ I/O thread pool associated with the
    /// socket’s context shall handle newly created connections. A value of zero specifies no
    /// affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the
    /// thread pool. For non-zero values, the lowest bit corresponds to thread 1, second lowest bit
    /// to thread 2 and so on. For example, a value of 3 specifies that subsequent connections on
    /// [`Socket`] shall be handled exclusively by I/O threads 1 and 2.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 0             | N/A                     |
    ///
    /// [`Socket`]: Socket
    /// [`Affinity`]: SocketOption::Affinity
    pub fn set_affinity(&self, value: u64) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::Affinity, value)
    }

    /// # Retrieve I/O thread affinity `ZMQ_AFFINITY`
    ///
    /// The [`Affinity`] option shall retrieve the I/O thread affinity for newly
    /// created connections on the specified [`Socket`].
    ///
    /// Affinity determines which threads from the 0MQ I/O thread pool associated with the
    /// socket’s context shall handle newly created connections. A value of zero specifies no
    /// affinity, meaning that work shall be distributed fairly among all 0MQ I/O threads in the
    /// thread pool. For non-zero values, the lowest bit corresponds to thread 1, second lowest bit
    /// to thread 2 and so on. For example, a value of 3 specifies that subsequent connections on
    /// [`Socket`] shall be handled exclusively by I/O threads 1 and 2.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 0             | N/A                     |
    ///
    /// [`Socket`]: Socket
    /// [`Affinity`]: SocketOption::Affinity
    pub fn affinity(&self) -> ZmqResult<u64> {
        self.get_sockopt_int(SocketOption::Affinity)
    }

    /// # Set maximum length of the queue of outstanding connections `ZMQ_BACKLOG`
    ///
    /// The [`Backlog`] option shall set the maximum length of the queue of outstanding peer
    /// connections for the specified [`Socket`]; this only applies to connection-oriented
    /// transports. For details refer to your operating system documentation for the `listen`
    /// function.
    ///
    /// | Default value           | Applicable socket types                       |
    /// | :---------------------: | :-------------------------------------------: |
    /// | 100                     | all, only for connection-oriented transports. |
    ///
    /// [`Socket`]: Socket
    /// [`Backlog`]: SocketOption::Backlog
    pub fn set_backlog(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::Backlog, value)
    }

    /// # Retrieve maximum length of the queue of outstanding connections `ZMQ_BACKLOG`
    ///
    /// The [`Backlog`] option shall retrieve the maximum length of the queue of outstanding peer
    /// connections for the specified [`Socket`]; this only applies to connection-oriented
    /// transports. For details refer to your operating system documentation for the `listen`
    /// function.
    ///
    /// | Default value           | Applicable socket types                       |
    /// | :---------------------: | :-------------------------------------------: |
    /// | 100                     | all, only for connection-oriented transports. |
    ///
    /// [`Socket`]: Socket
    /// [`Backlog`]: SocketOption::Backlog
    pub fn backlog(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::Backlog)
    }

    /// # This removes delays caused by the interrupt and the resultant context switch. `ZMQ_BUSY_POLL`
    ///
    /// Busy polling helps reduce latency in the network receive path by allowing socket layer code
    /// to poll the receive queue of a network device, and disabling network interrupts. This
    /// removes delays caused by the interrupt and the resultant context switch. However, it also
    /// increases CPU utilization. Busy polling also prevents the CPU from sleeping, which can
    /// incur additional power consumption.
    #[cfg(feature = "draft-api")]
    pub fn set_busy_poll(&self, value: bool) -> ZmqResult<()> {
        self.set_sockopt_bool(SocketOption::BusyPoll, value)
    }

    /// # Set connect() timeout `ZMQ_CONNECT_TIMEOUT`
    ///
    /// Sets how long to wait before timing-out a [`connect()`] system call. The [`connect()`]
    /// system call normally takes a long time before it returns a time out error. Setting this
    /// option allows the library to time out the call at an earlier interval.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | 0 ms (disabled)         | all, when using TCP transports. |
    ///
    /// [`connect()`]: #method.connect
    pub fn set_connect_timeout(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ConnectTimeout, value)
    }

    /// # Retrieve connect() timeout `ZMQ_CONNECT_TIMEOUT`
    ///
    /// Retrieves how long to wait before timing-out a [`connect()`] system call. The [`connect()`]
    /// system call normally takes a long time before it returns a time out error. Setting this
    /// option allows the library to time out the call at an earlier interval.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | 0 ms (disabled)         | all, when using TCP transports. |
    ///
    /// [`connect()`]: #method.connect
    pub fn connect_timeout(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ConnectTimeout)
    }

    /// # Retrieve socket event state `ZMQ_EVENTS`
    ///
    /// The [`events()`] option shall retrieve the event state for the specified `Socket`. The
    /// returned value is a bit mask constructed by OR’ing a combination of the following event
    /// flags:
    ///
    /// * [`POLL_IN`] Indicates that at least one message may be received from the specified socket
    ///   without blocking.
    /// * [`POLL_OUT`] Indicates that at least one message may be sent to the specified socket
    ///   without blocking.
    ///
    /// The combination of a file descriptor returned by the [`FileDescriptor`] option being ready
    /// for reading but no actual events returned by a subsequent retrieval of the [`events()`]
    /// option is valid; applications should simply ignore this case and restart their polling
    /// operation/event loop.
    ///
    /// | Default value | Applicable socket types         |
    /// | :-----------: | :-----------------------------: |
    /// | None          | all                             |
    ///
    /// [`events()`]: #method.events
    /// [`POLL_IN`]: PollEvents::POLL_IN
    /// [`POLL_OUT`]: PollEvents::POLL_OUT
    /// [`FileDescriptor`]: SocketOption::FileDescriptor
    pub fn events(&self) -> ZmqResult<PollEvents> {
        self.get_sockopt_int::<i32>(SocketOption::Events)?
            .try_into()
            .map(PollEvents::from_bits_truncate)
            .map_err(|_err| ZmqError::InvalidArgument)
    }

    /// # Disable GSSAPI encryption `ZMQ_GSSAPI_PLAINTEXT`
    ///
    /// Defines whether communications on the socket will be encrypted. A value of `true` means
    /// that communications will be plaintext. A value of `false` means communications will be
    /// encrypted.
    ///
    /// | Default value | Applicable socket types               |
    /// | :-----------: | :-----------------------------------: |
    /// | false         | all, when using TCP or IPC transports |
    #[cfg(zmq_has = "gssapi")]
    pub fn set_gssapi_plaintext(&self, value: bool) -> ZmqResult<()> {
        self.set_sockopt_bool(SocketOption::GssApiPlainText, value)
    }

    /// # Retrieve GSSAPI plaintext or encrypted status `ZMQ_GSSAPI_PLAINTEXT`
    ///
    /// Returns the [`gssapi_plaintext()`] option, if any, previously set on the socket. A value of
    /// `true` means that communications will be plaintext. A value of `false` means communications
    /// will be encrypted.
    ///
    /// | Default value | Applicable socket types               |
    /// | :-----------: | :-----------------------------------: |
    /// | false         | all, when using TCP or IPC transports |
    ///
    /// [`gssapi_plaintext()`]: #method.gssapi_plaintext
    #[cfg(zmq_has = "gssapi")]
    pub fn gssapi_plaintext(&self) -> ZmqResult<bool> {
        self.get_sockopt_bool(SocketOption::GssApiPlainText)
    }

    /// # Set name type of service principal `ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE`
    ///
    /// Sets the name type of the GSSAPI service principal. A value of [`NtHostbased`] means the
    /// name specified with [`GssApiServicePrincipal`] is interpreted as a host based name. A value
    /// of [`NtUsername`] means it is interpreted as a local user name. A value of
    /// [`NtKrb5Principal`] means it is interpreted as an unparsed principal name string (valid
    /// only with the krb5 GSSAPI mechanism).
    ///
    /// | Default value   | Applicable socket types               |
    /// | :-------------: | :-----------------------------------: |
    /// | [`NtHostbased`] | all, when using TCP or IPC transports |
    ///
    /// [`GssApiServicePrincipal`]: SocketOption::GssApiServicePrincipal
    /// [`NtHostbased`]: GssApiNametype::NtHostbased
    /// [`NtUsername`]: GssApiNametype::NtUsername
    /// [`NtKrb5Principal`]: GssApiNametype::NtKrb5Principal
    #[cfg(zmq_has = "gssapi")]
    pub fn set_gssapi_service_principal_nametype(&self, value: GssApiNametype) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::GssApiServicePrincipalNametype, value as i32)
    }

    /// # Retrieve nametype for service principal `ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE`
    ///
    /// Returns the [`GssApiServicePrincipalNametype`] option, if any, previously set on the socket.
    /// A value of [`NtHostbased`] means the name specified with [`GssApiServicePrincipal`] is
    /// interpreted as a host based name. A value of [`NtUsername`] means it is interpreted as a
    /// local user name. A value of [`NtKrb5Principal`] means it is interpreted as an unparsed
    /// principal name string (valid only with the krb5 GSSAPI mechanism).
    ///
    /// | Default value   | Applicable socket types               |
    /// | :-------------: | :-----------------------------------: |
    /// | [`NtHostbased`] | all, when using TCP or IPC transports |
    ///
    /// [`GssApiServicePrincipalNametype`]: SocketOption::GssApiServicePrincipalNametype
    /// [`GssApiServicePrincipal`]: SocketOption::GssApiServicePrincipal
    /// [`NtHostbased`]: GssApiNametype::NtHostbased
    /// [`NtUsername`]: GssApiNametype::NtUsername
    /// [`NtKrb5Principal`]: GssApiNametype::NtKrb5Principal
    #[cfg(zmq_has = "gssapi")]
    pub fn gssapi_service_principal_nametype(&self) -> ZmqResult<GssApiNametype> {
        self.get_sockopt_int::<i32>(SocketOption::GssApiServicePrincipalNametype)
            .and_then(GssApiNametype::try_from)
    }

    /// # Set name of GSSAPI principal `ZMQ_GSSAPI_PRINCIPAL`
    ///
    /// Sets the name of the principal for whom GSSAPI credentials should be acquired.
    ///
    /// | Default value   | Applicable socket types              |
    /// | :-------------: | :----------------------------------: |
    /// | not set         | all, when using TCP or IPC transport |
    #[cfg(zmq_has = "gssapi")]
    pub fn set_gssapi_principal<V>(&self, value: V) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        self.set_sockopt_string(SocketOption::GssApiPrincipal, value.as_ref())
    }

    /// # Retrieve the name of the GSSAPI principal `ZMQ_GSSAPI_PRINCIPAL`
    ///
    /// The [`gssapi_principal()`] option shall retrieve the principal name set for the GSSAPI
    /// security mechanism. The returned value shall be a NULL-terminated string and MAY be empty.
    /// The returned size SHALL include the terminating null byte.
    ///
    /// | Default value   | Applicable socket types              |
    /// | :-------------: | :----------------------------------: |
    /// | not set         | all, when using TCP or IPC transport |
    ///
    /// [`gssapi_principal()`]: #method.gssapi_principal
    #[cfg(zmq_has = "gssapi")]
    pub fn gssapi_principal(&self) -> ZmqResult<String> {
        self.socket
            .get_sockopt_gssapi(SocketOption::GssApiPrincipal.into())
    }

    /// # Set name type of principal `ZMQ_GSSAPI_PRINCIPAL_NAMETYPE`
    ///
    /// Sets the name type of the GSSAPI principal. A value of [`NtHostbased`] means the name
    /// specified with [`GssApiPrincipal`] is interpreted as a host based name. A value of
    /// [`NtUsername`] means it is interpreted as a local user name. A value of [`NtKrb5Principal`]
    /// means it is interpreted as an unparsed principal name string (valid only with the krb5
    /// GSSAPI mechanism).
    ///
    /// | Default value   | Applicable socket types               |
    /// | :-------------: | :-----------------------------------: |
    /// | [`NtHostbased`] | all, when using TCP or IPC transports |
    ///
    /// [`GssApiPrincipal`]: SocketOption::GssApiPrincipal
    /// [`NtHostbased`]: GssApiNametype::NtHostbased
    /// [`NtUsername`]: GssApiNametype::NtUsername
    /// [`NtKrb5Principal`]: GssApiNametype::NtKrb5Principal
    #[cfg(zmq_has = "gssapi")]
    pub fn set_gssapi_principal_nametype(&self, value: GssApiNametype) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::GssApiPrincipalNametype, value as i32)
    }

    /// # Retrieve nametype for service principal `ZMQ_GSSAPI_PRINCIPAL_NAMETYPE`
    ///
    /// Returns the [`GssApiPrincipalNametype`] option, if any, previously set on the socket. A
    /// value of [`NtHostbased`] means the name specified with [`GssApiPrincipal`] is
    /// interpreted as a host based name. A value of [`NtUsername`] means it is interpreted as a
    /// local user name. A value of [`NtKrb5Principal`] means it is interpreted as an unparsed
    /// principal name string (valid only with the krb5 GSSAPI mechanism).
    ///
    /// | Default value   | Applicable socket types               |
    /// | :-------------: | :-----------------------------------: |
    /// | [`NtHostbased`] | all, when using TCP or IPC transports |
    ///
    /// [`GssApiPrincipalNametype`]: SocketOption::GssApiPrincipalNametype
    /// [`GssApiPrincipal`]: SocketOption::GssApiPrincipal
    /// [`NtHostbased`]: GssApiNametype::NtHostbased
    /// [`NtUsername`]: GssApiNametype::NtUsername
    /// [`NtKrb5Principal`]: GssApiNametype::NtKrb5Principal
    #[cfg(zmq_has = "gssapi")]
    pub fn gssapi_principal_nametype(&self) -> ZmqResult<GssApiNametype> {
        self.get_sockopt_int::<i32>(SocketOption::GssApiPrincipalNametype)
            .and_then(GssApiNametype::try_from)
    }

    /// # Set maximum handshake interval `ZMQ_HANDSHAKE_IVL`
    ///
    /// The [`HandshakeInterval`] option shall set the maximum handshake interval for the `Socket`.
    /// Handshaking is the exchange of socket configuration information (socket type, routing id,
    /// security) that occurs when a connection is first opened, only for connection-oriented
    /// transports. If handshaking does not complete within the configured time, the connection
    /// shall be closed. The value `0` means no handshake time limit.
    ///
    /// | Default value | Applicable socket types                                     |
    /// | :-----------: | :---------------------------------------------------------: |
    /// | 30_000 ms     | all but [`Stream`], only for connection-oriented transports |
    ///
    /// [`HandshakeInterval`]: SocketOption::HandshakeInterval
    /// [`Stream`]: StreamSocket
    pub fn set_handshake_interval(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::HandshakeInterval, value)
    }

    /// # Retrieve maximum handshake interval `ZMQ_HANDSHAKE_IVL`
    ///
    /// The [`HandshakeInterval`] option shall retrieve the maximum handshake interval for the
    /// `Socket`. Handshaking is the exchange of socket configuration information (socket type,
    /// routing id, security) that occurs when a connection is first opened, only for
    /// connection-oriented transports. If handshaking does not complete within the configured
    /// time, the connection shall be closed. The value `0` means no handshake time limit.
    ///
    /// | Default value | Applicable socket types                                     |
    /// | :-----------: | :---------------------------------------------------------: |
    /// | 30_000 ms     | all but [`Stream`], only for connection-oriented transports |
    ///
    /// [`HandshakeInterval`]: SocketOption::HandshakeInterval
    /// [`Stream`]: StreamSocket
    pub fn handshake_interval(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::HandshakeInterval)
    }

    /// # Set interval between sending ZMTP heartbeats `ZMQ_HEARTBEAT_IVL`
    ///
    /// The [`HeartbeatInterval`] option shall set the interval between sending ZMTP heartbeats for
    /// the `Socket`. If this option is set and is greater than `0`, then a `PING` ZMTP command
    /// will be sent every [`heartbeat_interval()`] milliseconds.
    ///
    /// | Default value | Applicable socket types                        |
    /// | :-----------: | :--------------------------------------------: |
    /// | ß ms          | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    /// [`heartbeat_interval()`]: #method.heartbeat_interval
    pub fn set_heartbeat_interval(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::HeartbeatInterval, value)
    }

    /// # Retrieve interval between sending ZMTP heartbeats `ZMQ_HEARTBEAT_IVL`
    ///
    /// The [`HeartbeatInterval`] option returns the interval between sending ZMTP heartbeats for
    /// the `Socket`. If this option is set and is greater than `0`, then a `PING` ZMTP command
    /// will be sent every [`heartbeat_interval()`] milliseconds.
    ///
    /// | Default value | Applicable socket types                        |
    /// | :-----------: | :--------------------------------------------: |
    /// | ß ms          | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    /// [`heartbeat_interval()`]: #method.heartbeat_interval
    pub fn heartbeat_interval(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::HeartbeatInterval)
    }

    /// # Set timeout for ZMTP heartbeats `ZMQ_HEARTBEAT_TIMEOUT`
    ///
    /// The [`HeartbeatTimeout`] option shall set how long to wait before timing-out a connection
    /// after sending a `PING` ZMTP command and not receiving any traffic. This option is only
    /// valid if [`HeartbeatInterval`] is also set, and is greater than `0`. The connection will
    /// time out if there is no traffic received after sending the `PING` command, but the received
    /// traffic does not have to be a `PONG` command - any received traffic will cancel the timeout.
    ///
    /// | Default value                                     | Applicable socket types                        |
    /// | :-----------------------------------------------: | :--------------------------------------------: |
    /// | 0 ms normally, [`HeartbeatInterval`] if it is set | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatTimeout`]: SocketOption::HeartbeatTimeout
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    pub fn set_heartbeat_timeout(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::HeartbeatTimeout, value)
    }

    /// # Retrieve timeout for ZMTP heartbeats `ZMQ_HEARTBEAT_TIMEOUT`
    ///
    /// The [`HeartbeatTimeout`] option returns how long to wait before timing-out a connection
    /// after sending a `PING` ZMTP command and not receiving any traffic. The connection will time
    /// out if there is no traffic received after sending the `PING` command, but the received
    /// traffic does not have to be a `PONG` command - any received traffic will cancel the timeout.
    ///
    /// | Default value                                     | Applicable socket types                        |
    /// | :-----------------------------------------------: | :--------------------------------------------: |
    /// | 0 ms normally, [`HeartbeatInterval`] if it is set | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatTimeout`]: SocketOption::HeartbeatTimeout
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    pub fn heartbeat_timeout(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::HeartbeatTimeout)
    }

    /// # Set the TTL value for ZMTP heartbeats `ZMQ_HEARTBEAT_TTL`
    ///
    /// The [`HeartbeatTimeToLive`] option shall set the timeout on the remote peer for ZMTP
    /// heartbeats. If this option is greater than 0, the remote side shall time out the connection
    /// if it does not receive any more traffic within the TTL period. This option does not have
    /// any effect if [`HeartbeatInterval`] is not set or is `0`. Internally, this value is rounded
    /// down to the nearest decisecond, any value less than `100` will have no effect.
    ///
    /// | Default value                           | Applicable socket types                        |
    /// | :-------------------------------------: | :--------------------------------------------: |
    /// | 6_553_599 (which is 2^16-1 deciseconds) | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatTimeToLive`]: SocketOption::HeartbeatTimeToLive
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    pub fn set_heartbeat_timetolive(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::HeartbeatTimeToLive, value)
    }

    /// # Retrieve the TTL value for ZMTP heartbeats `ZMQ_HEARTBEAT_TTL`
    ///
    /// The [`HeartbeatTimeToLive`] option returns the timeout on the remote peer for ZMTP
    /// heartbeats. If this option is greater than 0, the remote side shall time out the connection
    /// if it does not receive any more traffic within the TTL period. This option does not have
    /// any effect if [`HeartbeatInterval`] is not set or is `0`. Internally, this value is rounded
    /// down to the nearest decisecond, any value less than `100` will have no effect.
    ///
    /// | Default value                           | Applicable socket types                        |
    /// | :-------------------------------------: | :--------------------------------------------: |
    /// | 6_553_599 (which is 2^16-1 deciseconds) | all, when using connection-oriented transports |
    ///
    /// [`HeartbeatTimeToLive`]: SocketOption::HeartbeatTimeToLive
    /// [`HeartbeatInterval`]: SocketOption::HeartbeatInterval
    pub fn heartbeat_timetolive(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::HeartbeatTimeToLive)
    }

    /// # Queue messages only to completed connections `ZMQ_IMMEDIATE`
    ///
    /// By default queues will fill on outgoing connections even if the connection has not
    /// completed. This can lead to "lost" messages on sockets with round-robin routing
    /// ([`Request`], [`Push`], [`Dealer`]). If this option is set to `true`, messages shall be
    /// queued only to completed connections. This will cause the socket to block if there are no
    /// other connections, but will prevent queues from filling on pipes awaiting connection.
    ///
    /// | Default value | Applicable socket types                        |
    /// | :-----------: | :--------------------------------------------: |
    /// | false         | all, when using connection-oriented transports |
    ///
    /// [`Request`]: RequestSocket
    /// [`Push`]: PushSocket
    /// [`Dealer`]: DealerSocket
    pub fn set_immediate(&self, value: bool) -> ZmqResult<()> {
        self.set_sockopt_bool(SocketOption::Immediate, value)
    }

    /// # Retrieve attach-on-connect value `ZMQ_IMMEDIATE`
    ///
    /// Retrieve the state of the attach on connect value. If set to 1`true`, will delay the
    /// attachment of a pipe on connect until the underlying connection has completed. This will
    /// cause the socket to block if there are no other connections, but will prevent queues from
    /// filling on pipes awaiting connection.
    ///
    /// | Default value | Applicable socket types                        |
    /// | :-----------: | :--------------------------------------------: |
    /// | false         | all, when using connection-oriented transports |
    pub fn immediate(&self) -> ZmqResult<bool> {
        self.get_sockopt_bool(SocketOption::Immediate)
    }

    /// # Enable IPv6 on socket `ZMQ_IPV6`
    ///
    /// Set the IPv6 option for the socket. A value of `true` means IPv6 is enabled on the socket,
    /// while `false` means the socket will use only IPv4. When IPv6 is enabled the socket will
    /// connect to, or accept connections from, both IPv4 and IPv6 hosts.
    ///
    /// | Default value | Applicable socket types         |
    /// | :-----------: | :-----------------------------: |
    /// | false         | all, when using TCP transports. |
    pub fn set_ipv6(&self, value: bool) -> ZmqResult<()> {
        self.set_sockopt_bool(SocketOption::IPv6, value)
    }

    /// # Retrieve IPv6 socket status `ZMQ_IPV6`
    ///
    /// Retrieve the IPv6 option for the socket. A value of `true` means IPv6 is enabled on the
    /// socket, while `false` means the socket will use only IPv4. When IPv6 is enabled the socket
    /// will connect to, or accept connections from, both IPv4 and IPv6 hosts.
    ///
    /// | Default value | Applicable socket types         |
    /// | :-----------: | :-----------------------------: |
    /// | false         | all, when using TCP transports. |
    pub fn ipv6(&self) -> ZmqResult<bool> {
        self.get_sockopt_bool(SocketOption::IPv6)
    }

    /// # Set linger period for socket shutdown `ZMQ_LINGER`
    ///
    /// The [`Linger`] option shall set the linger period for the `Socket`. The linger period
    /// determines how long pending messages which have yet to be sent to a peer shall linger in
    /// memory after a socket is disconnected with [`disconnect()`] or closed, and further affects
    /// the termination of the socket’s context. The following outlines the different behaviours:
    ///
    /// * A value of `-1` specifies an infinite linger period. Pending messages shall not be
    ///   discarded after a call to [`disconnect()`]; attempting to terminate the socket’s context
    ///   shall block until all pending messages have been sent to a peer.
    /// * The value of `0` specifies no linger period. Pending messages shall be discarded
    ///   immediately after a call to [`disconnect()`].
    /// * Positive values specify an upper bound for the linger period in milliseconds. Pending
    ///   messages shall not be discarded after a call to [`disconnect()`]; attempting to terminate
    ///   the socket’s context shall block until either all pending messages have been sent to a
    ///   peer, or the linger period expires, after which any pending messages shall be discarded.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1 (infinite) | all                     |
    ///
    /// [`disconnect()`]: #method.disconnect
    /// [`Linger`]: SocketOption::Linger
    pub fn set_linger(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::Linger, value)
    }

    /// # Retrieve linger period for socket shutdown `ZMQ_LINGER`
    ///
    /// The [`Linger`] option shall retrieve the linger period for the `Socket`. The linger period
    /// determines how long pending messages which have yet to be sent to a peer shall linger in
    /// memory after a socket is closed, and further affects the termination of the socket’s
    /// context. The following outlines the different behaviours:
    ///
    /// * A value of `-1` specifies an infinite linger period. Pending messages shall not be
    ///   discarded after a call to [`disconnect()`]; attempting to terminate the socket’s context
    ///   shall block until all pending messages have been sent to a peer.
    /// * The value of `0` specifies no linger period. Pending messages shall be discarded
    ///   immediately after a call to [`disconnect()`].
    /// * Positive values specify an upper bound for the linger period in milliseconds. Pending
    ///   messages shall not be discarded after a call to [`disconnect()`]; attempting to terminate
    ///   the socket’s context shall block until either all pending messages have been sent to a
    ///   peer, or the linger period expires, after which any pending messages shall be discarded.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1 (infinite) | all                     |
    ///
    /// [`disconnect()`]: #method.disconnect
    /// [`Linger`]: SocketOption::Linger
    pub fn linger(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::Linger)
    }

    /// # Retrieve the last endpoint set `ZMQ_LAST_ENDPOINT`
    ///
    /// The [`LastEndpoint`] option shall retrieve the last endpoint bound for TCP and IPC
    /// transports. The returned value will be a string in the form of a ZMQ DSN. Note that if the
    /// TCP host is INADDR_ANY, indicated by a *, then the returned address will be `0.0.0.0`
    /// (for IPv4). Note: not supported on GNU/Hurd with IPC due to non-working getsockname().
    ///
    /// | Default value | Applicable socket types                 |
    /// | :-----------: | :-------------------------------------: |
    /// | None          | all, when binding TCP or IPC transports |
    ///
    /// [`LastEndpoint`]: SocketOption::LastEndpoint
    pub fn last_endpoint(&self) -> ZmqResult<String> {
        self.get_sockopt_string(SocketOption::LastEndpoint)
    }

    /// # Maximum acceptable inbound message size `ZMQ_MAXMSGSIZE`
    ///
    /// Limits the size of the inbound message. If a peer sends a message larger than
    /// [`MaxMessageSize`] it is disconnected. Value of `-1` means 'no limit'.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1 (bytes)    | all                     |
    ///
    /// [`MaxMessageSize`]: SocketOption::MaxMessageSize
    pub fn set_max_message_size(&self, value: i64) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::MaxMessageSize, value)
    }

    /// # Maximum acceptable inbound message size `ZMQ_MAXMSGSIZE`
    ///
    /// The option shall retrieve limit for the inbound messages. If a peer sends a message larger
    /// than [`MaxMessageSize`] it is disconnected. Value of `-1` means 'no limit'.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1 (bytes)    | all                     |
    ///
    /// [`MaxMessageSize`]: SocketOption::MaxMessageSize
    pub fn max_message_size(&self) -> ZmqResult<i64> {
        self.get_sockopt_int(SocketOption::MaxMessageSize)
    }

    /// # Set the security mechanism `ZMQ_MECHANISM`
    ///
    /// Sets the security [`Mechanism`] option for the socket based on the provided
    /// [`SecurityMechanism`].
    ///
    /// [`Mechanism`]: SocketOption::Mechanism
    /// [ SecurityMechanism`]: SecurityMechanism
    pub fn set_security_mechanism(&self, security: &SecurityMechanism) -> ZmqResult<()> {
        security.apply(self)
    }

    /// # Retrieve current security mechanism `ZMQ_MECHANISM`
    ///
    /// The [`Mechanism`] option shall retrieve the current security mechanism for the socket.
    ///
    /// [`Mechanism`]: SocketOption::Mechanism
    pub fn security_mechanism(&self) -> ZmqResult<SecurityMechanism> {
        SecurityMechanism::try_from(self)
    }

    /// # Maximum network hops for multicast packets `ZMQ_MULTICAST_HOPS`
    ///
    /// Sets the time-to-live field in every multicast packet sent from this socket. The default
    /// is `1` which means that the multicast packets don’t leave the local network.
    ///
    /// | Default value | Applicable socket types              |
    /// | :-----------: | :----------------------------------: |
    /// | 1             | all, when using multicast transports |
    pub fn set_multicast_hops(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::MulticastHops, value)
    }

    /// # Maximum network hops for multicast packets `ZMQ_MULTICAST_HOPS`
    ///
    /// The option shall retrieve time-to-live used for outbound multicast packets. The default of
    /// `1` means that the multicast packets don’t leave the local network.
    ///
    /// | Default value | Applicable socket types              |
    /// | :-----------: | :----------------------------------: |
    /// | 1             | all, when using multicast transports |
    pub fn multicast_hops(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::MulticastHops)
    }

    /// # Set multicast data rate `ZMQ_RATE`
    ///
    /// The [`Rate`] option shall set the maximum send or receive data rate for multicast
    /// transports such as `pgm` using the `Socket`.
    ///
    /// | Default value      | Applicable socket types              |
    /// | :----------------: | :----------------------------------: |
    /// | 100 (kilobits/sec) | all, when using multicast transports |
    ///
    /// [`Rate`]: SocketOption::Rate
    pub fn set_rate(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::Rate, value)
    }

    /// # Retrieve multicast data rate `ZMQ_RATE`
    ///
    /// The [`Rate`] option shall retrieve the maximum send or receive data rate for multicast
    /// transports using the `Socket`.
    ///
    /// | Default value      | Applicable socket types              |
    /// | :----------------: | :----------------------------------: |
    /// | 100 (kilobits/sec) | all, when using multicast transports |
    ///
    /// [`Rate`]: SocketOption::Rate
    pub fn rate(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::Rate)
    }

    /// # Set kernel receive buffer size `ZMQ_RCVBUF`
    /// The [`ReceiveBuffer`] option shall set the underlying kernel receive buffer size for the
    /// `Socket` to the specified size in bytes. A value of `-1` means leave the OS default
    /// unchanged. For details refer to your operating system documentation for the `SO_RCVBUF`
    /// socket option.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1            | all                     |
    ///
    /// [`ReceiveBuffer`]: SocketOption::ReceiveBuffer
    pub fn set_receive_buffer(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReceiveBuffer, value)
    }

    /// # Retrieve kernel receive buffer size `ZMQ_RCVBUF`
    ///
    /// The [`ReceiveBuffer`] option shall retrieve the underlying kernel receive buffer size for
    /// the `Socket`. For details refer to your operating system documentation for the `SO_RCVBUF`
    /// socket option.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1            | all                     |
    ///
    /// [`ReceiveBuffer`]: SocketOption::ReceiveBuffer
    pub fn receive_buffer(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ReceiveBuffer)
    }

    /// # Set high water mark for inbound messages `ZMQ_RCVHWM`
    ///
    /// The [`ReceiveHighWatermark`] option shall set the high water mark for inbound messages on
    /// the `Ssocket`. The high water mark is a hard limit on the maximum number of outstanding
    /// messages 0MQ shall queue in memory for any single peer that the specified `Socket` is
    /// communicating with. A value of zero means no limit.
    ///
    /// If this limit has been reached the socket shall enter an exceptional state and depending on
    /// the socket type, 0MQ shall take appropriate action such as blocking or dropping sent
    /// messages. Refer to the individual socket descriptions for details on the exact action taken
    /// for each socket type.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 1000          | all                     |
    ///
    /// [`ReceiveHighWatermark`]: SocketOption::ReceiveHighWatermark
    pub fn set_receive_highwater_mark(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReceiveHighWatermark, value)
    }

    /// # Retrieve high water mark for inbound messages `ZMQ_RCVHWM`
    ///
    /// The [`ReceiveHighWatermark`] option shall return the high water mark for inbound messages
    /// on the `Socket`. The high water mark is a hard limit on the maximum number of outstanding
    /// messages 0MQ shall queue in memory for any single peer that the specified `Socket` is
    /// communicating with. A value of zero means no limit.
    ///
    /// If this limit has been reached the socket shall enter an exceptional state and depending on
    /// the socket type, 0MQ shall take appropriate action such as blocking or dropping sent
    /// messages. Refer to the individual socket descriptions for details on the exact action taken
    /// for each socket type.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 1000          | all                     |
    ///
    /// [`ReceiveHighWatermark`]: SocketOption::ReceiveHighWatermark
    pub fn receive_highwater_mark(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ReceiveHighWatermark)
    }

    ///# Maximum time before a recv operation returns with [`Again`] `ZMQ_RCVTIMEO`
    ///
    /// Sets the timeout for receive operation on the socket. If the value is 0, [`recv_msg()`]
    /// will return immediately, with a [`Again`] error if there is no message to receive. If the
    /// value is `-1`, it will block until a message is available. For all other values, it will
    /// wait for a message for that amount of time before returning with an [`Again`] error.
    ///
    /// | Default value    | Applicable socket types |
    /// | :--------------: | :---------------------: |
    /// | -1 ms (infinite) | all                     |
    ///
    /// [`Again`]: crate::ZmqError::Again
    /// [`recv_msg()`]: #method.recv_msg
    pub fn set_receive_timeout(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReceiveTimeout, value)
    }

    /// # Maximum time before a socket operation returns with [`Again`] `ZMQ_RCVTIMEO`
    ///
    /// Retrieve the timeout for recv operation on the socket. If the value is `0`, [`recv_msg()`]
    /// will return immediately, with a [`Again`] error if there is no message to receive. If the
    /// value is `-1`, it will block until a message is available. For all other values, it will
    /// wait for a message for that amount of time before returning with an [`Again`] error.
    ///
    /// | Default value    | Applicable socket types |
    /// | :--------------: | :---------------------: |
    /// | -1 ms (infinite) | all                     |
    ///
    /// [`Again`]: crate::ZmqError::Again
    /// [`recv_msg()`]: #method.recv_msg
    pub fn receive_timeout(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ReceiveTimeout)
    }

    /// # Set reconnection interval `ZMQ_RECONNECT_IVL`
    /// The [`ReconnectInterval`] option shall set the initial reconnection interval for the
    /// `Socket`. The reconnection interval is the period 0MQ shall wait between attempts to
    /// reconnect disconnected peers when using connection-oriented transports. The value `-1`
    /// means no reconnection.
    ///
    /// | Default value | Applicable socket types                      |
    /// | :-----------: | :------------------------------------------: |
    /// | 100 ms        | all, only for connection-oriented transports |
    ///
    /// [`ReconnectInterval`]: SocketOption::ReconnectInterval
    pub fn set_reconnect_interval(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReconnectInterval, value)
    }

    /// # Retrieve reconnection interval `ZMQ_RECONNECT_IVL`
    ///
    /// The [`ReconnectInterval`] option shall retrieve the initial reconnection interval for the
    /// `Socket`. The reconnection interval is the period 0MQ shall wait between attempts to
    /// reconnect disconnected peers when using connection-oriented transports. The value `-1`
    /// means no reconnection.
    ///
    /// | Default value | Applicable socket types                      |
    /// | :-----------: | :------------------------------------------: |
    /// | 100 ms        | all, only for connection-oriented transports |
    ///
    /// [`ReconnectInterval`]: SocketOption::ReconnectInterval
    pub fn reconnect_interval(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ReconnectInterval)
    }

    /// # Set max reconnection interval `ZMQ_RECONNECT_IVL_MAX`
    ///
    /// The [`ReconnectIntervalMax`] option shall set the max reconnection interval for the
    /// `Socket`. 0MQ shall wait at most the configured interval between reconnection attempts. The
    /// interval grows exponentionally (i.e.: it is doubled) with each attempt until it reaches
    /// [`ReconnectIntervalMax`]. Default value means that the reconnect interval is based
    /// exclusively on [`ReconnectInterval`] and no exponential backoff is performed.
    ///
    /// | Default value                             | Applicable socket types                      |
    /// | :---------------------------------------: | :------------------------------------------: |
    /// | 0 ms ([`ReconnectInterval`] will be used) | all, only for connection-oriented transports |
    ///
    /// [`ReconnectIntervalMax`]: SocketOption::ReconnectIntervalMax
    /// [`ReconnectInterval`]: SocketOption::ReconnectInterval
    pub fn set_reconnect_interval_max(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReconnectIntervalMax, value)
    }

    /// # Retrieve max reconnection interval `ZMQ_RECONNECT_IVL_MAX`
    ///
    /// The [`ReconnectIntervalMax`] option shall retrieve the max reconnection interval for the
    /// `Socket`. 0MQ shall wait at most the configured interval between reconnection attempts. The
    /// interval grows exponentionally (i.e.: it is doubled) with each attempt until it reaches
    /// [`ReconnectIntervalMax`]. Default value means that the reconnect interval is based
    /// exclusively on [`ReconnectInterval`] and no exponential backoff is performed.
    ///
    /// | Default value                             | Applicable socket types                      |
    /// | :---------------------------------------: | :------------------------------------------: |
    /// | 0 ms ([`ReconnectInterval`] will be used) | all, only for connection-oriented transports |
    ///
    /// [`ReconnectIntervalMax`]: SocketOption::ReconnectIntervalMax
    /// [`ReconnectInterval`]: SocketOption::ReconnectInterval
    pub fn reconnect_interval_max(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::ReconnectIntervalMax)
    }

    /// # Set condition where reconnection will stop `ZMQ_RECONNECT_STOP`
    ///
    /// The [`ReconnectStop`] option shall set the conditions under which automatic reconnection
    /// will stop. This can be useful when a process binds to a wild-card port, where the OS
    /// supplies an ephemeral port.
    ///
    /// | Default value | Applicable socket types                      |
    /// | :-----------: | :------------------------------------------: |
    /// | 0             | all, only for connection-oriented transports |
    ///
    /// [`ReconnectStop`]: SocketOption::ReconnectStop
    #[cfg(feature = "draft-api")]
    pub fn set_reconnect_stop(&self, value: ReconnectStop) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::ReconnectStop, value.bits())
    }

    /// # ZMQ_RECONNECT_STOP: Retrieve condition where reconnection will stop
    ///
    /// The [`ReconnectStop`] option shall retrieve the conditions under which automatic
    /// reconnection will stop.
    ///
    /// | Default value | Applicable socket types                      |
    /// | :-----------: | :------------------------------------------: |
    /// | 0             | all, only for connection-oriented transports |
    ///
    /// [`ReconnectStop`]: SocketOption::ReconnectStop
    #[cfg(feature = "draft-api")]
    pub fn reconnect_stop(&self) -> ZmqResult<ReconnectStop> {
        self.get_sockopt_int(SocketOption::ReconnectStop)
            .map(ReconnectStop::from_bits_truncate)
    }

    /// # Set multicast recovery interval `ZMQ_RECOVERY_IVL`
    ///
    /// The [`RecoveryInterval`] option shall set the recovery interval for multicast transports
    /// using the `Socket`. The recovery interval determines the maximum time in milliseconds that
    /// a receiver can be absent from a multicast group before unrecoverable data loss will occur.
    ///
    /// | Default value | Applicable socket types              |
    /// | :-----------: | :----------------------------------: |
    /// | 10_000 ms     | all, when using multicast transports |
    ///
    /// [`RecoveryInterval`]: SocketOption::RecoveryInterval
    pub fn set_recovery_interval(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::RecoveryInterval, value)
    }

    /// # Get multicast recovery interval `ZMQ_RECOVERY_IVL`
    ///
    /// The [`RecoveryInterval`] option shall retrieve the recovery interval for multicast
    /// transports using the `Socket`. The recovery interval determines the maximum time in
    /// milliseconds that a receiver can be absent from a multicast group before unrecoverable data
    /// loss will occur.
    ///
    /// | Default value | Applicable socket types              |
    /// | :-----------: | :----------------------------------: |
    /// | 10_000 ms     | all, when using multicast transports |
    ///
    /// [`RecoveryInterval`]: SocketOption::RecoveryInterval
    pub fn recovery_interval(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::RecoveryInterval)
    }

    /// # Set kernel transmit buffer size `ZMQ_SNDBUF`
    ///
    /// The [`SendBuffer`] option shall set the underlying kernel transmit buffer size for the
    /// `Socket` to the specified size in bytes. A value of `-1` means leave the OS default
    /// unchanged. For details please refer to your operating system documentation for the
    /// `SO_SNDBUF` socket option.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1            | all                     |
    ///
    /// [`SendBuffer`]: SocketOption::SendBuffer
    pub fn set_send_buffer(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::SendBuffer, value)
    }

    /// # Retrieve kernel transmit buffer size `ZMQ_SNDBUF`
    ///
    /// The [`SendBuffer`] option shall retrieve the underlying kernel transmit buffer size for the
    /// `Socket`. For details refer to your operating system documentation for the `SO_SNDBUF`
    /// socket option.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | -1            | all                     |
    ///
    /// [`SendBuffer`]: SocketOption::SendBuffer
    pub fn send_buffer(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::SendBuffer)
    }

    /// # Set high water mark for outbound messages `ZMQ_SNDHWM`
    ///
    /// The [`SendHighWatermark`] option shall set the high water mark for outbound messages on the
    /// `Socket`. The high water mark is a hard limit on the maximum number of outstanding messages
    /// 0MQ shall queue in memory for any single peer that the `Socket` is communicating with. A
    /// value of zero means no limit.
    ///
    /// If this limit has been reached the socket shall enter an exceptional state and depending on
    /// the socket type, 0MQ shall take appropriate action such as blocking or dropping sent
    /// messages. Refer to the individual socket descriptions for details on the exact action taken
    /// for each socket type.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 1000          | all                     |
    ///
    /// [`SendHighWatermark`]: SocketOption::SendHighWatermark
    pub fn set_send_highwater_mark(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::SendHighWatermark, value)
    }

    /// # Retrieves high water mark for outbound messages `ZMQ_SNDHWM`
    ///
    /// The [`SendHighWatermark`] option shall return the high water mark for outbound messages on
    /// the `Socket`. The high water mark is a hard limit on the maximum number of outstanding
    /// messages 0MQ shall queue in memory for any single peer that the `Socket` is communicating
    /// with. A value of zero means no limit.
    ///
    /// If this limit has been reached the socket shall enter an exceptional state and depending on
    /// the socket type, 0MQ shall take appropriate action such as blocking or dropping sent
    /// messages. Refer to the individual socket descriptions for details on the exact action taken
    /// for each socket type.
    ///
    /// | Default value | Applicable socket types |
    /// | :-----------: | :---------------------: |
    /// | 1000          | all                     |
    ///
    /// [`SendHighWatermark`]: SocketOption::SendHighWatermark
    pub fn send_highwater_mark(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::SendHighWatermark)
    }

    /// # Maximum time before a send operation returns with [`Again`] `ZMQ_SNDTIMEO`
    ///
    /// Sets the timeout for send operation on the socket. If the value is `0`, [`send_msg()`] will
    /// return immediately, with a [`Again`] error if the message cannot be sent. If the value is
    /// `-1`, it will block until the message is sent. For all other values, it will try to send
    /// the message for that amount of time before returning with an EAGAIN error.
    ///
    /// | Default value    | Applicable socket types |
    /// | :--------------: | :---------------------: |
    /// | -1 ms (infinite) | all                     |
    ///
    /// [`Again`]: crate::ZmqError::Again
    /// [`send_msg()`]: #method.send_msg
    pub fn set_send_timeout(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::SendTimeout, value)
    }

    /// # Maximum time before a socket operation returns with [`Again`] `ZMQ_SNDTIMEO`
    ///
    /// Retrieve the timeout for send operation on the socket. If the value is `0`, [`send_msg()`]
    /// will return immediately, with a [`Again`] error if the message cannot be sent. If the value
    /// is `-1`, it will block until the message is sent. For all other values, it will try to send
    /// the message for that amount of time before returning with an [`Again`] error.
    ///
    /// | Default value    | Applicable socket types |
    /// | :--------------: | :---------------------: |
    /// | -1 ms (infinite) | all                     |
    ///
    /// [`Again`]: crate::ZmqError::Again
    /// [`send_msg()`]: #method.send_msg
    pub fn send_timeout(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::SendTimeout)
    }

    /// # Set SOCKS5 proxy address `ZMQ_SOCKS_PROXY`
    ///
    /// Sets the SOCKS5 proxy address that shall be used by the socket for the TCP connection(s).
    /// Supported authentication methods are: no authentication or basic authentication when setup
    /// with [`SocksUsername`]. If the endpoints are domain names instead of addresses they shall
    /// not be resolved and they shall be forwarded unchanged to the SOCKS proxy service in the
    /// client connection request message (address type 0x03 domain name).
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    ///
    /// [`SocksUsername`]: SocketOption::SocksUsername
    #[cfg(feature = "draft-api")]
    pub fn set_socks_proxy<V>(&self, value: Option<V>) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        match value {
            None => self.set_sockopt_string(SocketOption::SocksUsername, ""),
            Some(ref_value) => self.set_sockopt_string(SocketOption::SocksProxy, ref_value),
        }
    }

    /// # Retrieve SOCKS5 proxy address `ZMQ_SOCKS_PROXY`
    ///
    /// The [`SocksProxy`] option shall retrieve the SOCKS5 proxy address in string format. The
    /// returned value MAY be empty.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    ///
    /// [`SocksProxy`]: SocketOption::SocksProxy
    #[cfg(feature = "draft-api")]
    pub fn socks_proxy(&self) -> ZmqResult<String> {
        self.get_sockopt_string(SocketOption::SocksProxy)
    }

    /// # Set SOCKS username and select basic authentication `ZMQ_SOCKS_USERNAME`
    ///
    /// Sets the username for authenticated connection to the SOCKS5 proxy. If you set this to a
    /// non-null and non-empty value, the authentication method used for the SOCKS5 connection
    /// shall be basic authentication. In this case, use [`set_socks_password()`] option in order
    /// to set the password. If you set this to a null value or empty value, the authentication
    /// method shall be no authentication, the default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    ///
    /// [`set_socks_password()`]: #method.set_socks_password
    #[cfg(feature = "draft-api")]
    pub fn set_socks_username<V>(&self, value: V) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        self.set_sockopt_string(SocketOption::SocksUsername, value.as_ref())
    }

    /// # Retrieve SOCKS username and select basic authentication `ZMQ_SOCKS_USERNAME`
    ///
    /// Returns the username for authenticated connection to the SOCKS5 proxy. If set to a non-null
    /// and non-empty value, the authentication method used for the SOCKS5 connection shall be
    /// basic authentication. If set to a null value or empty value, the authentication method
    /// shall be no authentication, the default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    #[cfg(feature = "draft-api")]
    pub fn socks_username(&self) -> ZmqResult<String> {
        self.get_sockopt_string(SocketOption::SocksUsername)
    }

    /// # Set SOCKS basic authentication password `ZMQ_SOCKS_PASSWORD`
    ///
    /// Sets the password for authenticating to the SOCKS5 proxy server. This is used only when the
    /// SOCK5 authentication method has been set to basic authentication through the
    /// [`set_socks_username()`] option. Setting this to a null value (the default) is equivalent
    /// to an empty password string.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    ///
    /// [`set_socks_username()`]: #method.set_socks_username
    #[cfg(feature = "draft-api")]
    pub fn set_socks_password<V>(&self, value: V) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        self.set_sockopt_string(SocketOption::SocksPassword, value.as_ref())
    }

    /// # Retrieve SOCKS basic authentication password `ZMQ_SOCKS_PASSWORD`
    ///
    /// Returns the password for authenticating to the SOCKS5 proxy server. This is used only when
    /// the SOCK5 authentication method has been set to basic authentication through the
    /// [`set_socks_username()`] option. A null value (the default) is equivalent to an empty
    /// password string.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | not set       | all, when using TCP transport |
    ///
    /// [`set_socks_username()`]: #method.set_socks_username
    #[cfg(feature = "draft-api")]
    pub fn socks_password(&self) -> ZmqResult<String> {
        self.get_sockopt_string(SocketOption::SocksPassword)
    }

    /// # Override `SO_KEEPALIVE` socket option `ZMQ_TCP_KEEPALIVE`
    ///
    /// Override `SO_KEEPALIVE` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn set_tcp_keepalive(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::TcpKeepalive, value)
    }

    /// # Override `SO_KEEPALIVE` socket option `ZMQ_TCP_KEEPALIVE`
    ///
    /// Override `SO_KEEPALIVE` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn tcp_keepalive(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::TcpKeepalive)
    }

    /// # Override `TCP_KEEPCNT` socket option `ZMQ_TCP_KEEPALIVE_CNT`
    ///
    /// Override `TCP_KEEPCNT` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn set_tcp_keepalive_count(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::TcpKeepaliveCount, value)
    }

    ///  Override `TCP_KEEPCNT` socket option `ZMQ_TCP_KEEPALIVE_CNT`
    ///
    /// Override `TCP_KEEPCNT` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn tcp_keepalive_count(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::TcpKeepaliveCount)
    }

    /// # Override `TCP_KEEPIDLE` (or `TCP_KEEPALIVE` on some OS) `ZMQ_TCP_KEEPALIVE_IDLE`
    ///
    /// Override `TCP_KEEPIDLE` (or `TCP_KEEPALIVE` on some OS) socket option (where supported by
    /// OS). The default value of `-1` means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn set_tcp_keepalive_idle(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::TcpKeepaliveIdle, value)
    }

    /// # Override `TCP_KEEPIDLE` (or `TCP_KEEPALIVE` on some OS) `ZMQ_TCP_KEEPALIVE_IDLE`
    ///
    /// Override `TCP_KEEPIDLE` (or `TCP_KEEPALIVE` on some OS) socket option (where supported by
    /// OS). The default value of `-1` means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn tcp_keepalive_idle(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::TcpKeepaliveIdle)
    }

    /// # Override `TCP_KEEPINTVL` socket option `ZMQ_TCP_KEEPALIVE_INTVL`
    ///
    /// Override `TCP_KEEPINTVL` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn set_tcp_keepalive_interval(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::TcpKeepaliveInterval, value)
    }

    /// # Override `TCP_KEEPINTVL` socket option `ZMQ_TCP_KEEPALIVE_INTVL`
    ///
    /// Override `TCP_KEEPINTVL` socket option (where supported by OS). The default value of `-1`
    /// means to skip any overrides and leave it to OS default.
    ///
    /// | Default value | Applicable socket types       |
    /// | :-----------: | :---------------------------: |
    /// | -1            | all, when using TCP transport |
    pub fn tcp_keepalive_interval(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::TcpKeepaliveInterval)
    }

    /// # Set TCP Maximum Retransmit Timeout `ZMQ_TCP_MAXRT`
    ///
    /// On OSes where it is supported, sets how long before an unacknowledged TCP retransmit times
    /// out. The system normally attempts many TCP retransmits following an exponential backoff
    /// strategy. This means that after a network outage, it may take a long time before the
    /// session can be re-established. Setting this option allows the timeout to happen at a
    /// shorter interval.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | 0 ms                    | all, when using TCP transports. |
    pub fn set_tcp_max_retransmit_timeout(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::MaxTcpRetransmitTimeout, value)
    }

    /// # Retrieve Max TCP Retransmit Timeout `ZMQ_TCP_MAXRT`
    ///
    /// On OSes where it is supported, retrieves how long before an unacknowledged TCP retransmit
    /// times out. The system normally attempts many TCP retransmits following an exponential
    /// backoff strategy. This means that after a network outage, it may take a long time before
    /// the session can be re-established. Setting this option allows the timeout to happen at a
    /// shorter interval.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | 0 ms                    | all, when using TCP transports. |
    pub fn tcp_max_retransmit_timeout(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::MaxTcpRetransmitTimeout)
    }

    /// # Set the Type-of-Service on socket `ZMQ_TOS`
    ///
    /// Sets the ToS fields (Differentiated services (DS) and Explicit Congestion Notification
    /// (ECN) field of the IP header. The ToS field is typically used to specify a packets
    /// priority. The availability of this option is dependent on intermediate network equipment
    /// that inspect the ToS field and provide a path for low-delay, high-throughput,
    /// highly-reliable service, etc.
    ///
    /// | Default value           | Applicable socket types                      |
    /// | :---------------------: | :------------------------------------------: |
    /// | 0                       | all, only for connection-oriented transports |
    pub fn set_type_of_service(&self, value: i32) -> ZmqResult<()> {
        self.set_sockopt_int(SocketOption::TypeOfService, value)
    }

    /// # Retrieve the Type-of-Service socket override status `ZMQ_TOS`
    ///
    /// Retrieve the IP_TOS option for the socket.
    ///
    /// | Default value           | Applicable socket types                      |
    /// | :---------------------: | :------------------------------------------: |
    /// | 0                       | all, only for connection-oriented transports |
    pub fn type_of_service(&self) -> ZmqResult<i32> {
        self.get_sockopt_int(SocketOption::TypeOfService)
    }

    /// # Set RFC 27 authentication domain `ZMQ_ZAP_DOMAIN`
    ///
    /// Sets the domain for ZAP (ZMQ RFC 27) authentication. A ZAP domain must be specified to
    /// enable authentication. When the ZAP domain is empty, which is the default, ZAP
    /// authentication is disabled.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | empty                   | all, when using TCP transports. |
    pub fn set_zap_domain(&self, domain: &ZapDomain) -> ZmqResult<()> {
        domain.apply(self)
    }

    /// # Retrieve RFC 27 authentication domain `ZMQ_ZAP_DOMAIN`
    ///
    /// The [`zap_domain()`] option shall retrieve the last ZAP domain set for the socket. The
    /// returned value shall be a NULL-terminated string and MAY be empty. An empty string means
    /// that ZAP authentication is disabled. The returned size SHALL include the terminating null
    /// byte.
    ///
    /// | Default value           | Applicable socket types         |
    /// | :---------------------: | :-----------------------------: |
    /// | not set                 | all, when using TCP transports. |
    ///
    /// [`zap_domain()`]: #method.zap_domain
    pub fn zap_domain(&self) -> ZmqResult<ZapDomain> {
        self.get_sockopt_string(SocketOption::ZapDomain)
            .map(ZapDomain::from)
    }

    /// # accept incoming connections on a socket
    ///
    /// The [`bind()`] function binds the `Socket` to a local `endpoint` and then accepts incoming
    /// connections on that endpoint.
    ///
    /// The `endpoint` is a string consisting of a `transport://` followed by an `address`. The
    /// `transport` specifies the underlying protocol to use. The `address` specifies the
    /// transport-specific address to bind to.
    ///
    /// 0MQ provides the following transports:
    ///
    /// * `tcp` unicast transport using TCP
    /// * `ipc` local inter-process communication transport
    /// * `inproc` local in-process (inter-thread) communication transport
    /// * `pgm`, `epgm` reliable multicast transport using PGM
    /// * `vmci` virtual machine communications interface (VMCI)
    /// * `udp` unreliable unicast and multicast using UDP
    ///
    /// Every 0MQ socket type except [`Pair`] and [`Channel`] supports one-to-many and many-to-one
    /// semantics.
    ///
    /// The `ipc`, `tcp`, `vmci` and `udp` transports accept wildcard addresses.
    ///
    /// [`bind()`]: #method.bind
    /// [`Pair`]: PairSocket
    /// [`Channel`]: ChannelSocket
    pub fn bind<E>(&self, endpoint: E) -> ZmqResult<()>
    where
        E: AsRef<str>,
    {
        self.socket.bind(endpoint.as_ref())
    }

    /// # Stop accepting connections on a socket
    ///
    /// The [`unbind()`] function shall unbind a socket from the endpoint specified by the
    /// `endpoint` argument.
    ///
    /// Additionally the incoming message queue associated with the endpoint will be discarded.
    /// This means that after unbinding an endpoint it is possible to received messages originating
    /// from that same endpoint if they were already present in the incoming message queue before
    /// unbinding.
    ///
    /// The `endpoint` argument is as described in [`bind()`].
    ///
    /// ## Unbinding wild-card address from a socket
    ///
    /// When wild-card * `endpoint` was used in [`bind()`], the caller should use real `endpoint`
    /// obtained from the [`last_endpoint()`] socket option to unbind this `endpoint` from a socket.
    ///
    /// [`unbind()`]: #method.unbind
    /// [`bind()`]: #method.bind
    /// [`last_endpoint()`]: #method.last_endpoint
    pub fn unbind<E>(&self, endpoint: E) -> ZmqResult<()>
    where
        E: AsRef<str>,
    {
        self.socket.unbind(endpoint.as_ref())
    }

    /// # create outgoing connection from socket
    ///
    /// The [`connect()`] function connects the `Socket` to an `endpoint` and then accepts incoming
    /// connections on that endpoint.
    ///
    /// The `endpoint` is a string consisting of a `transport://` followed by an `address`. The
    /// `transport` specifies the underlying protocol to use. The `address` specifies the
    /// transport-specific address to connect to.
    ///
    /// 0MQ provides the the following transports:
    ///
    /// * `tcp` unicast transport using TCP
    /// * `ipc` local inter-process communication transport
    /// * `inproc` local in-process (inter-thread) communication transport
    /// * `pgm`, `epgm` reliable multicast transport using PGM
    /// * `vmci` virtual machine communications interface (VMCI)
    /// * `udp` unreliable unicast and multicast using UDP
    ///
    /// Every 0MQ socket type except [`Pair`] and [`Channel`] supports one-to-many and many-to-one
    /// semantics.
    ///
    /// [`connect()`]: #method.connect
    /// [`Pair`]: PairSocket
    /// [`Channel`]: ChannelSocket
    pub fn connect<E>(&self, endpoint: E) -> ZmqResult<()>
    where
        E: AsRef<str>,
    {
        self.socket.connect(endpoint.as_ref())
    }

    /// # Disconnect a socket from an endpoint
    ///
    /// The [`disconnect()`] function shall disconnect a socket from the endpoint specified by the
    /// `endpoint` argument. Note the actual disconnect system call might occur at a later time.
    ///
    /// Upon disconnection the will also stop receiving messages originating from this endpoint.
    /// Moreover, the socket will no longer be able to queue outgoing messages to this endpoint.
    /// The outgoing message queue associated with the endpoint will be discarded. However, if the
    /// socket’s [`linger()`] period is non-zero, libzmq will still attempt to transmit these discarded
    /// messages, until the linger period expires.
    ///
    /// The `endpoint` argument is as described in [`connect()`]
    ///
    /// [`disconnect()`]: #method.disconnect
    /// [`linger()`]: #method.linger
    /// [`connect()`]: #method.connect
    pub fn disconnect<E>(&self, endpoint: E) -> ZmqResult<()>
    where
        E: AsRef<str>,
    {
        self.socket.disconnect(endpoint.as_ref())
    }

    /// # monitor socket events
    ///
    /// The [`monitor()`] method lets an application thread track socket events (like connects) on
    /// a ZeroMQ socket. Each call to this method creates a [`Monitor`] socket connected to the
    /// socket.
    ///
    /// The `events` argument is a bitmask of the socket events you wish to monitor. To monitor all
    /// events, use the event value [`MonitorFlags::all()`]. NOTE: as new events are added, the
    /// catch-all value will start returning them. An application that relies on a strict and fixed
    /// sequence of events must not use [`MonitorFlags::all()`] in order to guarantee compatibility
    /// with future versions.
    ///
    /// [`monitor()`]: #method.monitor
    /// [`Monitor`]: MonitorSocket
    /// [`MonitorFlags::all()`]: MonitorFlags::all
    pub fn monitor<F>(&self, events: F) -> ZmqResult<MonitorSocket>
    where
        F: Into<MonitorFlags>,
    {
        let fd = self.get_sockopt_int::<usize>(SocketOption::FileDescriptor)?;
        let monitor_endpoint = format!("inproc://monitor.s-{fd}");

        self.socket
            .monitor(&monitor_endpoint, events.into().bits() as i32)?;

        let monitor = RawSocket::from_ctx(
            self.context.as_raw(),
            <Monitor as sealed::SocketType>::raw_socket_type() as i32,
        )?;

        monitor.connect(&monitor_endpoint)?;

        Ok(Socket {
            context: self.context.clone(),
            socket: monitor.into(),
            marker: PhantomData,
        })
    }

    /// # input/output multiplexing
    ///
    /// Poll this socket for input/output events.
    pub fn poll<E>(&self, events: E, timeout_ms: i64) -> ZmqResult<PollEvents>
    where
        E: Into<PollEvents>,
    {
        self.socket
            .poll(events.into(), timeout_ms)?
            .try_into()
            .map(PollEvents::from_bits_truncate)
            .map_err(|_err| ZmqError::InvalidArgument)
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, From, Default, PartialEq, Eq, PartialOrd, Ord)]
#[from(u16)]
/// Flags for setting up monitor sockets
pub struct MonitorFlags(u16);

bitflags! {
    impl MonitorFlags: u16 {
        /// The socket has successfully connected to a remote peer. The event value is the file
        /// descriptor (FD) of the underlying network socket.
        ///
        /// <div class="warning">
        ///
        /// Warning:
        ///
        /// There is no guarantee that the FD is still valid by the time your code receives this
        /// event.
        ///
        /// </div>
        const Connected                 = 0b0000_0000_0000_0001;
        /// A connect request on the socket is pending. The event value is unspecified.
        const ConnectDelayed            = 0b0000_0000_0000_0010;
        /// A connect request failed, and is now being retried. The event value is the reconnect
        /// interval in milliseconds.
        ///
        /// Note that the reconnect interval is recalculated at each retry.
        const ConnectRetried            = 0b0000_0000_0000_0100;
        /// The socket was successfully bound to a network interface. The event value is the FD of
        /// the underlying network socket.
        ///
        /// <div class="warning">
        ///
        /// Warning:
        ///
        /// There is no guarantee that the FD is still valid by the time your code receives this
        /// event.
        ///
        /// </div>
        const Listening                 = 0b0000_0000_0000_1000;
        /// The socket could not bind to a given interface. The event value is the errno generated
        /// by the system bind call.
        const BindFailed                = 0b0000_0000_0001_0000;
        /// The socket has accepted a connection from a remote peer. The event value is the FD of
        /// the underlying network socket.
        ///
        /// <div class="warning">
        ///
        /// Warning:
        ///
        /// There is no guarantee that the FD is still valid by the time your code receives this
        /// event.
        ///
        /// </div>
        const Accepted                  = 0b0000_0000_0010_0000;
        /// The socket has rejected a connection from a remote peer. The event value is the errno
        /// generated by the accept call.
        const AcceptFailed              = 0b0000_0000_0100_0000;
        /// The socket was closed. The event value is the FD of the (now closed) network socket.
        const Closed                    = 0b0000_0000_1000_0000;
        /// The socket close failed. The event value is the errno returned by the system call.
        ///
        /// Note that this event occurs only on IPC transports.
        const CloseFailed               = 0b0000_0001_0000_0000;
        /// The socket was disconnected unexpectedly. The event value is the FD of the underlying
        /// network socket.
        ///
        /// <div class="warning">
        ///
        /// Warning:
        ///
        /// This socket will be closed.
        ///
        /// </div>
        const Disconnected              = 0b0000_0010_0000_0000;
        /// Monitoring on this socket ended.
        const MonitorStopped            = 0b0000_0100_0000_0000;
        /// Unspecified error during handshake. The event value is an errno.
        const HandshakeFailedNoDetail   = 0b0000_1000_0000_0000;
        /// The ZMTP security mechanism handshake succeeded. The event value is unspecified.
        const HandshakeSucceeded        = 0b0001_0000_0000_0000;
        /// The ZMTP security mechanism handshake failed due to some mechanism protocol error,
        /// either between the ZMTP mechanism peers, or between the mechanism server and the ZAP
        /// handler. This indicates a configuration or implementation error in either peer resp.
        /// the ZAP handler.
        const HandshakeFailedProtocol   = 0b0010_0000_0000_0000;
        /// The ZMTP security mechanism handshake failed due to an authentication failure. The
        /// event value is the status code returned by the ZAP handler (i.e. `300`, `400` or `500`).
        const HandshakeFailedAuth       = 0b0100_0000_0000_0000;
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, From, Default, PartialEq, Eq, PartialOrd, Ord)]
/// Flag options for receive operations
pub struct RecvFlags(i32);

bitflags! {
    impl RecvFlags: i32 {
        /// Specifies that the operation should be performed in non-blocking mode.
        const DONT_WAIT = 0b00000001;
    }
}

#[cfg_attr(feature = "futures", async_trait)]
/// Trait for receiving single part messages
pub trait Receiver {
    fn recv_msg<F>(&self, flags: F) -> ZmqResult<Message>
    where
        F: Into<RecvFlags> + Copy;

    #[cfg(feature = "futures")]
    async fn recv_msg_async(&self) -> Option<Message>;
}

#[cfg_attr(feature = "futures", async_trait)]
impl<T> Receiver for Socket<T>
where
    T: sealed::SocketType + sealed::ReceiverFlag + Unpin,
    Socket<T>: Sync,
{
    fn recv_msg<F>(&self, flags: F) -> ZmqResult<Message>
    where
        F: Into<RecvFlags> + Copy,
    {
        self.socket
            .recv(flags.into().bits())
            .map(Message::from_raw_msg)
    }

    #[cfg(feature = "futures")]
    async fn recv_msg_async(&self) -> Option<Message> {
        futures::MessageReceivingFuture { receiver: self }.now_or_never()
    }
}

#[cfg_attr(feature = "futures", async_trait)]
/// Trait for receiving multipart messages
pub trait MultipartReceiver: Receiver {
    fn recv_multipart<F>(&self, flags: F) -> ZmqResult<MultipartMessage>
    where
        F: Into<RecvFlags> + Copy,
    {
        iter::repeat_with(|| self.recv_msg(flags))
            .try_fold(
                MultipartMessage::new(),
                |mut parts, zmq_result| match zmq_result {
                    Err(e) => ControlFlow::Break(Err(e)),
                    Ok(zmq_msg) => {
                        let got_more = zmq_msg.get_more();
                        parts.push_back(zmq_msg);
                        if got_more {
                            ControlFlow::Continue(parts)
                        } else {
                            ControlFlow::Break(Ok(parts))
                        }
                    }
                },
            )
            .break_value()
            .unwrap()
    }

    #[cfg(feature = "futures")]
    async fn recv_multipart_async(&self) -> MultipartMessage {
        ::futures::stream::repeat_with(|| Ok(self.recv_msg_async()))
            .try_fold(MultipartMessage::new(), |mut parts, zmq_msg| async move {
                if let Some(msg) = zmq_msg.await {
                    let got_more = msg.get_more();
                    parts.push_back(msg);
                    if !got_more {
                        return Err(parts);
                    }
                }
                Ok(parts)
            })
            .await
            .unwrap_err()
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, From, Default, PartialEq, Eq, PartialOrd, Ord)]
/// Flag options for send operations
pub struct SendFlags(i32);

bitflags! {
    impl SendFlags: i32 {
        /// For socket types ([`Dealer`], [`Push`]) that block (either with [`Immediate`] option
        /// set and no peer available, or all peers having full high-water mark), specifies that
        /// the operation should be performed in non-blocking mode.
        ///
        /// [`Dealer`]: DealerSocket
        /// [`Push`]: PushSocket
        /// [`Immediate`]: SocketOption::Immediate
        const DONT_WAIT = 0b00000001;
        /// Specifies that the message being sent is a multi-part message, and that further message
        /// parts are to follow.
        const SEND_MORE = 0b00000010;
    }
}

#[cfg_attr(feature = "futures", async_trait)]
/// Trait for sending single part messages
pub trait Sender {
    fn send_msg<M, F>(&self, msg: M, flags: F) -> ZmqResult<()>
    where
        M: Into<Message>,
        F: Into<SendFlags> + Copy;

    #[cfg(feature = "futures")]
    async fn send_msg_async<M, F>(&self, msg: M, flags: F) -> Option<()>
    where
        M: Into<Message> + Clone + Send,
        F: Into<SendFlags> + Copy + Send;
}

#[cfg_attr(feature = "futures", async_trait)]
impl<T> Sender for Socket<T>
where
    T: sealed::SocketType + sealed::SenderFlag + Unpin,
    Socket<T>: Sync,
{
    fn send_msg<M, F>(&self, msg: M, flags: F) -> ZmqResult<()>
    where
        M: Into<Message>,
        F: Into<SendFlags> + Copy,
    {
        msg.into().send(self, flags.into().bits())
    }

    #[cfg(feature = "futures")]
    async fn send_msg_async<M, F>(&self, msg: M, flags: F) -> Option<()>
    where
        M: Into<Message> + Clone + Send,
        F: Into<SendFlags> + Copy + Send,
    {
        futures::MessageSendingFuture {
            receiver: self,
            message: msg,
            flags: flags.into(),
        }
        .now_or_never()
    }
}

#[cfg_attr(feature = "futures", async_trait)]
/// Trait for sending multipart messages
pub trait MultipartSender: Sender {
    fn send_multipart<M, F>(&self, iter: M, flags: F) -> ZmqResult<()>
    where
        M: Into<MultipartMessage>,
        F: Into<SendFlags> + Copy,
    {
        let mut last_part: Option<Message> = None;
        for part in iter.into() {
            let maybe_last = last_part.take();
            if let Some(last) = maybe_last {
                self.send_msg(last, flags.into() | SendFlags::SEND_MORE)?;
            }
            last_part = Some(part);
        }
        if let Some(last) = last_part {
            self.send_msg(last, flags)
        } else {
            Ok(())
        }
    }

    #[cfg(feature = "futures")]
    async fn send_multipart_async<M, F>(&self, multipart: M, flags: F) -> Option<()>
    where
        M: Into<MultipartMessage> + Send,
        F: Into<SendFlags> + Copy + Send,
    {
        let mut last_part = None;
        for part in multipart.into() {
            let maybe_last = last_part.take();
            if let Some(last) = maybe_last {
                self.send_msg_async(last, flags.into() | SendFlags::SEND_MORE)
                    .await?;
            }
            last_part = Some(part);
        }
        if let Some(last) = last_part {
            self.send_msg_async(last, flags.into()).await
        } else {
            None
        }
    }
}

#[cfg(feature = "futures")]
mod futures {
    use core::{pin::Pin, task::Poll};

    use super::{RecvFlags, SendFlags, Socket};
    use crate::{
        message::{Message, Sendable},
        sealed,
    };

    pub(super) struct MessageSendingFuture<'a, T, M>
    where
        T: sealed::SocketType + sealed::SenderFlag + Unpin,
        M: Into<Message> + Clone + Send,
    {
        pub(super) receiver: &'a Socket<T>,
        pub(super) message: M,
        pub(super) flags: SendFlags,
    }

    #[rustversion::attr(before(1.87), allow(clippy::needless_lifetimes))]
    impl<'a, T, M> Future for MessageSendingFuture<'a, T, M>
    where
        T: sealed::SocketType + sealed::SenderFlag + Unpin,
        M: Into<Message> + Clone + Send,
    {
        type Output = ();

        fn poll(self: Pin<&mut Self>, _ctx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
            let message = self.message.clone().into();

            message
                .send(self.receiver, self.flags.bits())
                .map_or(Poll::Pending, Poll::Ready)
        }
    }

    pub(super) struct MessageReceivingFuture<'a, T>
    where
        T: sealed::SocketType + sealed::ReceiverFlag + Unpin,
    {
        pub(super) receiver: &'a Socket<T>,
    }

    impl<T> Future for MessageReceivingFuture<'_, T>
    where
        T: sealed::SocketType + sealed::ReceiverFlag + Unpin,
    {
        type Output = Message;

        fn poll(self: Pin<&mut Self>, _ctx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
            self.receiver
                .socket
                .recv(RecvFlags::DONT_WAIT.bits())
                .map(Message::from_raw_msg)
                .map_or(Poll::Pending, Poll::Ready)
        }
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, From, Default, PartialEq, Eq, PartialOrd, Ord)]
/// Flags for poll operations on sockets
pub struct PollEvents(i16);

bitflags! {
    impl PollEvents: i16 {
        /// For 0MQ sockets, at least one message may be received from the `Socket` without
        /// blocking. For standard sockets this is equivalent to the `POLLIN` flag of the `poll()`
        /// system call and generally means that at least one byte of data may be read from `fd`
        /// without blocking.
        const POLL_IN = 0b0000_0001;
        /// For 0MQ sockets, at least one message may be sent to the `Socket` without blocking. For
        /// standard sockets this is equivalent to the `POLLOUT` flag of the `poll()` system call
        /// and generally means that at least one byte of data may be written to `fd` without
        /// blocking.
        const POLL_OUT = 0b0000_0010;
        /// For standard sockets, this flag is passed to the underlying `poll()` system call and
        /// generally means that some sort of error condition is present on the socket specified by
        /// `fd`. For 0MQ sockets this flag has no effect if set in `events`.
        const POLL_ERR = 0b0000_0100;
        /// For 0MQ sockets this flags is of no use. For standard sockets this means there isurgent data to read. Refer to the POLLPRI flag for more information. For filedescriptor, refer to your use case: as an example, GPIO interrupts are signaled througha POLLPRI event. This flag has no effect on Windows.
        const POLL_PRI = 0b0000_1000;
    }
}

#[cfg(feature = "draft-api")]
#[repr(transparent)]
#[derive(Debug, Clone, Copy, From, Default, PartialEq, Eq, PartialOrd, Ord)]
/// Flags for the [`ReconnectStop`] socket option
///
/// [`ReconnectStop`]: SocketOption::ReconnectStop
pub struct ReconnectStop(i32);

#[cfg(feature = "draft-api")]
bitflags! {
    impl ReconnectStop: i32 {
        /// The [`CONNECTION_REFUSED`] option will stop reconnection when 0MQ receives the
        /// [`ConnectionRefused`] return code from the connect. This indicates that there is no
        /// code bound to the specified endpoint.
        ///
        /// [`CONNECTION_REFUSED`]: ReconnectStop::CONNECTION_REFUSED
        /// [`ConnectionRefused`]: crate::ZmqError::ConnectionRefused
        const CONNECTION_REFUSED = zmq_sys_crate::ZMQ_RECONNECT_STOP_CONN_REFUSED as i32;
        /// The [`HANDSHAKE_FAILED`] option will stop reconnection if the 0MQ handshake fails. This
        /// can be used to detect and/or prevent errant connection attempts to non-0MQ sockets.
        /// Note that when specifying this option you may also want to set [`HandshakeInterval`]
        /// — the default handshake interval is 30000 (30 seconds), which is typically too large.
        ///
        /// [`HANDSHAKE_FAILED`]: ReconnectStop::HANDSHAKE_FAILED
        /// [`HandshakeInterval`]: SocketOption::HandshakeInterval
        const HANDSHAKE_FAILED = zmq_sys_crate::ZMQ_RECONNECT_STOP_HANDSHAKE_FAILED as i32;
        /// The [`AFTER_DISCONNECT`] option will stop reconnection when `disconnect()` has been
        /// called. This can be useful when the user’s request failed (server not ready), as the
        /// socket does not need to continue to reconnect after user disconnect actively.
        ///
        /// [`AFTER_DISCONNECT`]: ReconnectStop::AFTER_DISCONNECT
        const AFTER_DISCONNECT = zmq_sys_crate::ZMQ_RECONNECT_STOP_AFTER_DISCONNECT as i32;
}}

#[cfg(test)]
mod socket_tests {
    use std::{thread, time::Duration};

    #[cfg(feature = "draft-api")]
    use rstest::*;

    #[cfg(feature = "draft-api")]
    use super::ReconnectStop;
    use super::{
        DealerSocket, MonitorFlags, MonitorSocketEvent, PairSocket, PollEvents, SendFlags,
    };
    #[cfg(zmq_has = "gssapi")]
    use crate::security::GssApiNametype;
    use crate::{
        prelude::{Context, MonitorReceiver, Sender, ZmqResult},
        security::SecurityMechanism,
    };

    #[test]
    fn set_affinity_sets_affinity() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_affinity(42)?;

        assert_eq!(socket.affinity()?, 42);

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[test]
    fn set_backlog_sets_backlog() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_backlog(42)?;

        assert_eq!(socket.backlog()?, 42);

        Ok(())
    }

    #[test]
    fn set_connect_timeout_sets_connect_timeout() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_connect_timeout(42)?;

        assert_eq!(socket.connect_timeout()?, 42);

        Ok(())
    }

    #[test]
    fn events_when_no_events_available() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;

        assert_eq!(socket.events()?, PollEvents::empty());

        Ok(())
    }

    #[test]
    fn events_when_connected() -> ZmqResult<()> {
        let context = Context::new()?;

        let endpoint = "inproc://test";
        let server_socket = PairSocket::from_context(&context)?;
        server_socket.bind(endpoint)?;

        let client_socket = PairSocket::from_context(&context)?;
        client_socket.connect(endpoint)?;

        assert_eq!(client_socket.events()?, PollEvents::POLL_OUT);

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn set_gssapi_plaintext_sets_gssapi_plaintext() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_gssapi_plaintext(true)?;

        assert!(socket.gssapi_plaintext()?);

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn set_gssapi_service_principal_sets_gssapi_service_principal() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_gssapi_service_principal_nametype(GssApiNametype::NtUsername)?;

        assert_eq!(
            socket.gssapi_service_principal_nametype()?,
            GssApiNametype::NtUsername
        );

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn set_gssapi_principal_sets_gssapi_principal() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_gssapi_principal("test")?;

        assert_eq!(socket.gssapi_principal()?, "test");

        Ok(())
    }

    #[cfg(zmq_has = "gssapi")]
    #[test]
    fn set_gssapi_principal_nametype_sets_gssapi_principal_nametype() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_gssapi_principal_nametype(GssApiNametype::NtHostbased)?;

        assert_eq!(
            socket.gssapi_principal_nametype()?,
            GssApiNametype::NtHostbased
        );

        Ok(())
    }

    #[test]
    fn set_handshake_interval_sets_handshake_interval() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_handshake_interval(42)?;

        assert_eq!(socket.handshake_interval()?, 42);

        Ok(())
    }

    #[test]
    fn set_heartbeat_interval_sets_heartbeat_interval() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_heartbeat_interval(42)?;

        assert_eq!(socket.heartbeat_interval()?, 42);

        Ok(())
    }

    #[test]
    fn set_heartbeat_timeout_sets_heartbeat_timeout() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_heartbeat_timeout(42)?;

        assert_eq!(socket.heartbeat_timeout()?, 42);

        Ok(())
    }

    #[test]
    fn set_heartbeat_timetolive_sets_heartbeat_ttl() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_heartbeat_timetolive(42_000)?;

        assert_eq!(socket.heartbeat_timetolive()?, 42_000);

        Ok(())
    }

    #[test]
    fn set_immediate_sets_immediate() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_immediate(true)?;

        assert!(socket.immediate()?);

        Ok(())
    }

    #[test]
    fn set_ipv6_sets_ipv6() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_ipv6(true)?;

        assert!(socket.ipv6()?);

        Ok(())
    }

    #[test]
    fn set_linger_sets_linger() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_linger(42)?;

        assert_eq!(socket.linger()?, 42);

        Ok(())
    }

    #[test]
    fn last_endpoint_when_not_bound_or_connected() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;

        assert_eq!(socket.last_endpoint()?, "");

        Ok(())
    }

    #[test]
    fn last_endpoint_when_bound() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.bind("inproc://last-endpoint-test")?;

        assert_eq!(socket.last_endpoint()?, "inproc://last-endpoint-test");

        Ok(())
    }

    #[test]
    fn set_max_msg_size_sets_max_msg_size() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_max_message_size(42)?;

        assert_eq!(socket.max_message_size()?, 42);

        Ok(())
    }

    #[test]
    fn set_security_mechanism_set_security_mechanism() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_security_mechanism(&SecurityMechanism::Plain {
            username: "username".into(),
            password: "supersecret".into(),
        })?;

        assert_eq!(
            socket.security_mechanism()?,
            SecurityMechanism::Plain {
                username: "username".into(),
                password: "supersecret".into()
            }
        );

        Ok(())
    }

    #[test]
    fn set_multicast_hops_sets_multicast_hops() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_multicast_hops(42)?;

        assert_eq!(socket.multicast_hops()?, 42);

        Ok(())
    }

    #[test]
    fn set_rate_sets_rate() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_rate(42)?;

        assert_eq!(socket.rate()?, 42);

        Ok(())
    }

    #[test]
    fn set_receive_buffer_sets_receive_buffer() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_receive_buffer(42)?;

        assert_eq!(socket.receive_buffer()?, 42);

        Ok(())
    }

    #[test]
    fn set_receive_high_watermark_sets_receive_high_watermark() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_receive_highwater_mark(42)?;

        assert_eq!(socket.receive_highwater_mark()?, 42);

        Ok(())
    }

    #[test]
    fn set_receive_timeout_sets_receive_timeout() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_receive_timeout(42)?;

        assert_eq!(socket.receive_timeout()?, 42);

        Ok(())
    }

    #[test]
    fn set_reconnect_interval_sets_reconnect_interval() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_reconnect_interval(42)?;

        assert_eq!(socket.reconnect_interval()?, 42);

        Ok(())
    }

    #[test]
    fn set_reconnect_interval_max_sets_reconnect_interval_max() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_reconnect_interval_max(42)?;

        assert_eq!(socket.reconnect_interval_max()?, 42);

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[test]
    fn set_reconnect_stop_sets_reconnect_stop() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_reconnect_stop(
            ReconnectStop::AFTER_DISCONNECT | ReconnectStop::CONNECTION_REFUSED,
        )?;

        assert_eq!(
            socket.reconnect_stop()?,
            ReconnectStop::AFTER_DISCONNECT | ReconnectStop::CONNECTION_REFUSED
        );

        Ok(())
    }

    #[test]
    fn set_recoveery_interval_sets_recovery_interval() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_recovery_interval(42)?;

        assert_eq!(socket.recovery_interval()?, 42);

        Ok(())
    }

    #[test]
    fn set_send_buffer_sets_send_buffer() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_send_buffer(42)?;

        assert_eq!(socket.send_buffer()?, 42);

        Ok(())
    }

    #[test]
    fn set_send_high_watermark_sets_send_high_watermark() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_send_highwater_mark(42)?;

        assert_eq!(socket.send_highwater_mark()?, 42);

        Ok(())
    }

    #[test]
    fn set_send_timeout_sets_send_timeout() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_send_timeout(42)?;

        assert_eq!(socket.send_timeout()?, 42);

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[rstest]
    #[case(None)]
    #[case(Some("asdf"))]
    fn set_socks_proxy_sets_proxy_value(#[case] socks_proxy: Option<&str>) -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_socks_proxy(socks_proxy)?;

        assert_eq!(socket.socks_proxy()?, socks_proxy.unwrap_or(""));

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[test]
    fn set_socks_username_sets_proxy_username() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_socks_username("username")?;

        assert_eq!(socket.socks_username()?, "username");

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[test]
    fn set_socks_password_sets_proxy_password() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_socks_password("password")?;

        assert_eq!(socket.socks_password()?, "password");

        Ok(())
    }

    #[test]
    fn set_tcp_keepalive_sets_tcp_keepalive() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_tcp_keepalive(1)?;

        assert_eq!(socket.tcp_keepalive()?, 1);

        Ok(())
    }

    #[test]
    fn set_tcp_keepalive_count_sets_tcp_keepalive_count() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_tcp_keepalive_count(42)?;

        assert_eq!(socket.tcp_keepalive_count()?, 42);

        Ok(())
    }

    #[test]
    fn set_tcp_keepalive_idle_sets_tcp_keepalive_idle() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_tcp_keepalive_idle(42)?;

        assert_eq!(socket.tcp_keepalive_idle()?, 42);

        Ok(())
    }

    #[test]
    fn set_tcp_keepalive_interval_sets_tcp_keepalive_interval() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_tcp_keepalive_interval(42)?;

        assert_eq!(socket.tcp_keepalive_interval()?, 42);

        Ok(())
    }

    #[test]
    fn set_tcp_max_retransmit_timout_set_retransmit_timeout() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_tcp_max_retransmit_timeout(42)?;

        assert_eq!(socket.tcp_max_retransmit_timeout()?, 42);

        Ok(())
    }

    #[test]
    fn set_type_of_service_sets_type_of_service() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_type_of_service(42)?;

        assert_eq!(socket.type_of_service()?, 42);

        Ok(())
    }

    #[test]
    fn set_zap_domain_sets_zap_domain() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;
        socket.set_zap_domain(&"zap".into())?;

        assert_eq!(socket.zap_domain()?, "zap".into());

        Ok(())
    }

    #[test]
    fn unbind_unbinds_endpoint() -> ZmqResult<()> {
        let context = Context::new()?;

        let endpoint = "inproc://unbind-test";

        let socket = PairSocket::from_context(&context)?;
        socket.bind(endpoint)?;

        assert!(socket.unbind(endpoint).is_ok());

        Ok(())
    }

    #[test]
    fn connect_connects_to_endpoint() -> ZmqResult<()> {
        let context = Context::new()?;

        let endpoint = "inproc://connect-test";

        let server_socket = PairSocket::from_context(&context)?;
        server_socket.bind(endpoint)?;

        let client_socket = PairSocket::from_context(&context)?;
        assert!(client_socket.connect(endpoint).is_ok());

        Ok(())
    }

    #[test]
    fn disconnect_disconnects_from_endpoint() -> ZmqResult<()> {
        let context = Context::new()?;

        let endpoint = "inproc://disconnect-test";
        let server_socket = PairSocket::from_context(&context)?;
        server_socket.bind(endpoint)?;

        let client_socket = PairSocket::from_context(&context)?;
        client_socket.connect(endpoint)?;
        assert!(client_socket.disconnect(endpoint).is_ok());

        Ok(())
    }

    #[test]
    fn monitor_sets_up_socket_monitor() -> ZmqResult<()> {
        let context = Context::new()?;

        let dealer_server = DealerSocket::from_context(&context)?;
        dealer_server.bind("tcp://127.0.0.1:*")?;
        let client_endpoint = dealer_server.last_endpoint()?;

        thread::spawn(move || {
            loop {
                thread::sleep(Duration::from_millis(10));
            }
        });

        let dealer_client = DealerSocket::from_context(&context)?;
        let dealer_monitor = dealer_client.monitor(MonitorFlags::Connected)?;

        dealer_client.connect(client_endpoint)?;

        loop {
            match dealer_monitor.recv_monitor_event() {
                Err(_) => continue,
                Ok(event) => {
                    assert_eq!(event, MonitorSocketEvent::Connected);
                    break;
                }
            }
        }

        Ok(())
    }

    #[cfg(feature = "futures")]
    #[test]
    fn monitor_sets_up_async_socket_monitor() -> ZmqResult<()> {
        let context = Context::new()?;

        let dealer_server = DealerSocket::from_context(&context)?;
        dealer_server.bind("tcp://127.0.0.1:*")?;
        let client_endpoint = dealer_server.last_endpoint()?;

        thread::spawn(move || {
            loop {
                thread::sleep(Duration::from_millis(10));
            }
        });

        futures::executor::block_on(async {
            let dealer_client = DealerSocket::from_context(&context)?;
            let dealer_monitor = dealer_client.monitor(MonitorFlags::Connected)?;

            dealer_client.connect(client_endpoint)?;

            loop {
                match dealer_monitor.recv_monitor_event_async().await {
                    Some(event) => {
                        assert_eq!(event, MonitorSocketEvent::Connected);
                        break;
                    }
                    _ => continue,
                }
            }

            Ok(())
        })
    }

    #[test]
    fn poll_on_socket_when_no_events_available() -> ZmqResult<()> {
        let context = Context::new()?;

        let socket = PairSocket::from_context(&context)?;

        assert_eq!(socket.poll(PollEvents::all(), 0)?, PollEvents::empty());

        Ok(())
    }

    #[test]
    fn poll_on_socket_when_event_available() -> ZmqResult<()> {
        let context = Context::new()?;

        let endpoint = "inproc://poll-test";
        let pair_server = PairSocket::from_context(&context)?;
        pair_server.bind(endpoint)?;

        let pair_client = PairSocket::from_context(&context)?;
        pair_client.connect(endpoint)?;

        pair_server.send_msg("msg1", SendFlags::empty())?;
        pair_server.send_msg("msg2", SendFlags::empty())?;
        pair_server.send_msg("msg3", SendFlags::empty())?;

        assert_eq!(pair_client.poll(PollEvents::all(), 0)?, PollEvents::POLL_IN);

        Ok(())
    }
}

#[cfg(feature = "builder")]
pub(crate) mod builder {
    use derive_builder::Builder;
    use serde::{Deserialize, Serialize};

    use crate::{
        ZmqResult, auth::ZapDomain, context::Context, sealed, security::SecurityMechanism,
        socket::Socket,
    };

    #[derive(Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Builder)]
    #[builder(
        pattern = "owned",
        name = "SocketBuilder",
        public,
        build_fn(skip, error = "ZmqError"),
        derive(PartialEq, Eq, Hash, Clone, serde::Serialize, serde::Deserialize)
    )]
    #[builder_struct_attr(doc = "Builder for [`Socket`].\n\n")]
    #[allow(dead_code)]
    struct SocketConfig {
        #[cfg(feature = "draft-api")]
        #[builder(default = false)]
        busy_poll: bool,
        #[builder(setter(into), default = 0)]
        connect_timeout: i32,
        #[builder(setter(into), default = 30_000)]
        handshake_interval: i32,
        #[builder(setter(into), default = 0)]
        heartbeat_interval: i32,
        #[builder(setter(into), default = 0)]
        heartbeat_timeout: i32,
        #[builder(setter(into), default = 0)]
        heartbeat_timetolive: i32,
        #[builder(default = false)]
        immediate: bool,
        #[builder(default = false)]
        ipv6: bool,
        #[builder(setter(into), default = 0)]
        linger: i32,
        #[builder(setter(into), default = -1)]
        max_message_size: i64,
        #[builder(setter(into), default = -1)]
        receive_buffer: i32,
        #[builder(setter(into), default = 1_000)]
        receive_highwater_mark: i32,
        #[builder(setter(into), default = -1)]
        receive_timeout: i32,
        #[builder(setter(into), default = 100)]
        reconnect_interval: i32,
        #[builder(setter(into), default = 0)]
        reconnect_interval_max: i32,
        #[builder(setter(into), default = -1)]
        send_buffer: i32,
        #[builder(setter(into), default = 1_000)]
        send_highwater_mark: i32,
        #[builder(setter(into), default = -1)]
        send_timeout: i32,
        #[builder(setter(into))]
        zap_domain: ZapDomain,
        #[builder(default = "SecurityMechanism::Null")]
        security_mechanism: SecurityMechanism,
    }

    impl SocketBuilder {
        /// Applies this builder to the provided socket
        pub fn apply<T>(self, socket: &Socket<T>) -> ZmqResult<()>
        where
            T: sealed::SocketType,
        {
            #[cfg(feature = "draft-api")]
            self.busy_poll
                .iter()
                .try_for_each(|busy_poll| socket.set_busy_poll(*busy_poll))?;

            self.connect_timeout
                .iter()
                .try_for_each(|connect_timeout| socket.set_connect_timeout(*connect_timeout))?;

            self.handshake_interval
                .iter()
                .try_for_each(|handshake_interval| {
                    socket.set_handshake_interval(*handshake_interval)
                })?;

            self.heartbeat_interval
                .iter()
                .try_for_each(|heartbeat_interval| {
                    socket.set_heartbeat_interval(*heartbeat_interval)
                })?;

            self.heartbeat_timeout
                .iter()
                .try_for_each(|heartbeat_timeout| {
                    socket.set_heartbeat_timeout(*heartbeat_timeout)
                })?;

            self.heartbeat_timetolive
                .iter()
                .try_for_each(|heartbeat_timetolive| {
                    socket.set_heartbeat_timetolive(*heartbeat_timetolive)
                })?;

            self.immediate
                .iter()
                .try_for_each(|immediate| socket.set_immediate(*immediate))?;

            self.ipv6
                .iter()
                .try_for_each(|ipv6| socket.set_ipv6(*ipv6))?;

            self.linger
                .iter()
                .try_for_each(|linger| socket.set_linger(*linger))?;

            self.max_message_size
                .iter()
                .try_for_each(|max_message_size| socket.set_max_message_size(*max_message_size))?;

            self.receive_buffer
                .iter()
                .try_for_each(|receive_buffer| socket.set_receive_buffer(*receive_buffer))?;

            self.receive_highwater_mark
                .iter()
                .try_for_each(|receive_highwater_mark| {
                    socket.set_receive_highwater_mark(*receive_highwater_mark)
                })?;

            self.receive_timeout
                .iter()
                .try_for_each(|receive_timeout| socket.set_receive_timeout(*receive_timeout))?;

            self.reconnect_interval
                .iter()
                .try_for_each(|reconnect_interval| {
                    socket.set_reconnect_interval(*reconnect_interval)
                })?;

            self.reconnect_interval_max
                .iter()
                .try_for_each(|reconnect_interval_max| {
                    socket.set_reconnect_interval_max(*reconnect_interval_max)
                })?;

            self.send_buffer
                .iter()
                .try_for_each(|send_buffer| socket.set_send_buffer(*send_buffer))?;

            self.send_highwater_mark
                .iter()
                .try_for_each(|send_highwater_mark| {
                    socket.set_send_highwater_mark(*send_highwater_mark)
                })?;

            self.send_timeout
                .iter()
                .try_for_each(|send_timeout| socket.set_send_timeout(*send_timeout))?;

            self.zap_domain
                .iter()
                .try_for_each(|zap_domain| socket.set_zap_domain(zap_domain))?;

            self.security_mechanism
                .iter()
                .try_for_each(|security_mechanism| {
                    socket.set_security_mechanism(security_mechanism)
                })?;

            Ok(())
        }

        pub fn build_from_context<T>(self, context: &Context) -> ZmqResult<Socket<T>>
        where
            T: sealed::SocketType,
        {
            let socket = Socket::<T>::from_context(context)?;

            self.apply(&socket)?;

            Ok(socket)
        }
    }

    #[cfg(test)]
    mod socket_builder_tests {
        use super::SocketBuilder;
        use crate::{
            auth::ZapDomain,
            prelude::{Context, PairSocket, ZmqResult},
            security::SecurityMechanism,
        };

        #[test]
        fn default_socket_builder() -> ZmqResult<()> {
            let context = Context::new()?;

            let builder = SocketBuilder::default();
            let socket = PairSocket::from_context(&context)?;

            builder.apply(&socket)?;

            assert_eq!(socket.connect_timeout()?, 0);
            assert_eq!(socket.handshake_interval()?, 30_000);
            assert_eq!(socket.heartbeat_interval()?, 0);
            assert_eq!(socket.heartbeat_timeout()?, -1);
            assert_eq!(socket.heartbeat_timetolive()?, 0);
            assert!(!socket.immediate()?);
            assert!(!socket.ipv6()?);
            assert_eq!(socket.linger()?, -1);
            assert_eq!(socket.max_message_size()?, -1);
            assert_eq!(socket.receive_buffer()?, -1);
            assert_eq!(socket.receive_highwater_mark()?, 1_000);
            assert_eq!(socket.receive_timeout()?, -1);
            assert_eq!(socket.reconnect_interval()?, 100);
            assert_eq!(socket.reconnect_interval_max()?, 0);
            assert_eq!(socket.send_buffer()?, -1);
            assert_eq!(socket.send_highwater_mark()?, 1_000);
            assert_eq!(socket.send_timeout()?, -1);
            assert_eq!(socket.zap_domain()?, ZapDomain::new("".into()));
            assert_eq!(socket.security_mechanism()?, SecurityMechanism::Null);

            Ok(())
        }

        #[test]
        fn builder_with_custom_setttings() -> ZmqResult<()> {
            let context = Context::new()?;

            let builder = SocketBuilder::default()
                .connect_timeout(42)
                .handshake_interval(21)
                .heartbeat_interval(666)
                .heartbeat_timeout(1337)
                .heartbeat_timetolive(420)
                .immediate(true)
                .ipv6(true)
                .linger(1337)
                .max_message_size(1337)
                .receive_buffer(1337)
                .receive_highwater_mark(1337)
                .receive_timeout(1337)
                .reconnect_interval(1337)
                .reconnect_interval_max(1337)
                .send_buffer(1337)
                .send_highwater_mark(1337)
                .send_timeout(1337)
                .zap_domain(ZapDomain::new("test".into()))
                .security_mechanism(SecurityMechanism::Plain {
                    username: "username".into(),
                    password: "supersecret".into(),
                });
            let socket = PairSocket::from_context(&context)?;

            builder.apply(&socket)?;

            assert_eq!(socket.connect_timeout()?, 42);
            assert_eq!(socket.handshake_interval()?, 21);
            assert_eq!(socket.heartbeat_interval()?, 666);
            assert_eq!(socket.heartbeat_timeout()?, 1337);
            assert_eq!(socket.heartbeat_timetolive()?, 400);
            assert!(socket.immediate()?);
            assert!(socket.ipv6()?);
            assert_eq!(socket.linger()?, 1337);
            assert_eq!(socket.max_message_size()?, 1337);
            assert_eq!(socket.receive_buffer()?, 1337);
            assert_eq!(socket.receive_highwater_mark()?, 1337);
            assert_eq!(socket.receive_timeout()?, 1337);
            assert_eq!(socket.reconnect_interval()?, 1337);
            assert_eq!(socket.reconnect_interval_max()?, 1337);
            assert_eq!(socket.send_buffer()?, 1337);
            assert_eq!(socket.send_highwater_mark()?, 1337);
            assert_eq!(socket.send_timeout()?, 1337);
            assert_eq!(socket.zap_domain()?, ZapDomain::new("test".into()));
            assert_eq!(
                socket.security_mechanism()?,
                SecurityMechanism::Plain {
                    username: "username".into(),
                    password: "supersecret".into()
                }
            );

            Ok(())
        }
    }
}