oiio-sys 0.4.1

Rust sys bindings for OpenImageIO https://github.com/AcademySoftwareFoundation/OpenImageIO
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
#include "ffi_imageio.h"
#include "ffi_pixel.h"
#include "oiio-sys/src/imageio.rs.h"
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/string_view.h>
#include <cstddef>
#include <limits>
#include <memory>
#include <stdexcept>
#include <stdio.h>

namespace oiio {
#pragma region ROI
ROI
roi_default() noexcept
{
    return ROI();
}

ROI
roi_new(int xbegin, int xend, int ybegin, int yend, int zbegin, int zend,
        int chbegin, int chend) noexcept
{
    return OIIO::ROI(xbegin, xend, ybegin, yend, zbegin, zend, chbegin, chend);
}

ROI
roi_new_all() noexcept
{
    return OIIO::ROI::All();
}

bool
roi_defined(const ROI& roi) noexcept
{
    return roi.defined();
}

int
roi_width(const ROI& roi) noexcept
{
    return roi.width();
}

int
roi_height(const ROI& roi) noexcept
{
    return roi.height();
}

int
roi_depth(const ROI& roi) noexcept
{
    return roi.depth();
}

int
roi_nchannels(const ROI& roi) noexcept
{
    return roi.nchannels();
}

uint64_t
roi_npixels(const ROI& roi) noexcept
{
    return roi.npixels();
}

bool
roi_eq_roi(const ROI& roi, const ROI& other) noexcept
{
    return roi == other;
}

bool
roi_ne_roi(const ROI& roi, const ROI& other) noexcept
{
    return roi != other;
}

bool
roi_contains(const ROI& roi, int x, int y, int z, int ch) noexcept
{
    return roi.contains(x, y, z, ch);
}

bool
roi_contains_roi(const ROI& roi, const ROI& other) noexcept
{
    return roi.contains(other);
}

ROI
roi_union(const ROI& roi, const ROI& other) noexcept
{
    return OIIO::roi_union(roi, other);
}

ROI
roi_intersection(const ROI& roi, const ROI& other) noexcept
{
    return OIIO::roi_intersection(roi, other);
}
#pragma endregion

#pragma region ImageSpec
std::unique_ptr<ImageSpec>
imagespec_from_resolution(int xres, int yres, int nchans)
{
    OIIO::ImageSpec* spec = new OIIO::ImageSpec(xres, yres, nchans);
    return std::unique_ptr<ImageSpec>(spec);
}

int
imagespec_x(const ImageSpec& spec)
{
    return spec.x;
}

int
imagespec_y(const ImageSpec& spec)
{
    return spec.y;
}

int
imagespec_z(const ImageSpec& spec)
{
    return spec.z;
}

int
imagespec_width(const ImageSpec& spec)
{
    return spec.width;
}

int
imagespec_height(const ImageSpec& spec)
{
    return spec.height;
}

int
imagespec_depth(const ImageSpec& spec)
{
    return spec.depth;
}

int
imagespec_full_x(const ImageSpec& spec)
{
    return spec.full_x;
}

int
imagespec_full_y(const ImageSpec& spec)
{
    return spec.full_y;
}

int
imagespec_full_z(const ImageSpec& spec)
{
    return spec.full_z;
}

int
imagespec_full_width(const ImageSpec& spec)
{
    return spec.full_width;
}

int
imagespec_full_height(const ImageSpec& spec)
{
    return spec.full_height;
}

int
imagespec_full_depth(const ImageSpec& spec)
{
    return spec.full_depth;
}

int
imagespec_tile_width(const ImageSpec& spec)
{
    return spec.tile_width;
}

int
imagespec_tile_height(const ImageSpec& spec)
{
    return spec.tile_height;
}

int
imagespec_tile_depth(const ImageSpec& spec)
{
    return spec.tile_depth;
}

int
imagespec_nchannels(const ImageSpec& spec)
{
    return spec.nchannels;
}

int
imagespec_alpha_channel(const ImageSpec& spec)
{
    return spec.alpha_channel;
}

int
imagespec_z_channel(const ImageSpec& spec)
{
    return spec.z_channel;
}

bool
imagespec_deep(const ImageSpec& spec)
{
    return spec.deep;
}

bool
imagespec_valid(const ImageSpec& spec)
{
    return spec.format != OIIO::TypeDesc::UNKNOWN;
}

std::unique_ptr<std::vector<std::string>>
imagespec_channel_names(const ImageSpec& spec)
{
    std::vector<std::string>* channel_names = new std::vector<std::string>(
        spec.channelnames);
    return std::unique_ptr<std::vector<std::string>>(channel_names);
}

rust::Slice<const TypeDesc>
imagespec_channelformats(const ImageSpec& spec)
{
    // An empty vector's data pointer may be null, which rust::Slice must not
    // carry; hand back a default slice instead, as the deep shims do.
    if (spec.channelformats.empty())
        return rust::Slice<const TypeDesc>();
    return rust::Slice<const TypeDesc>(spec.channelformats.data(),
                                       spec.channelformats.size());
}

namespace {
inline OIIO::string_view
to_string_view(const rust::Str text) noexcept
{
    return OIIO::string_view(text.data(), text.size());
}
}  // namespace

std::unique_ptr<ImageSpec>
imagespec_new(int xres, int yres, int nchans, TypeDesc format)
{
    return std::make_unique<ImageSpec>(xres, yres, nchans, format);
}

std::unique_ptr<ImageSpec>
imagespec_copy(const ImageSpec& spec)
{
    return std::make_unique<ImageSpec>(spec);
}

TypeDesc
imagespec_format(const ImageSpec& spec)
{
    return spec.format;
}

void
imagespec_set_format(ImageSpec& spec, TypeDesc format)
{
    spec.set_format(format);
}

void
imagespec_set_origin(ImageSpec& spec, int x, int y, int z)
{
    spec.x = x;
    spec.y = y;
    spec.z = z;
}

void
imagespec_set_dimensions(ImageSpec& spec, int width, int height, int depth)
{
    spec.width  = width;
    spec.height = height;
    spec.depth  = depth;
}

void
imagespec_set_full(ImageSpec& spec, int full_x, int full_y, int full_z,
                   int full_width, int full_height, int full_depth)
{
    spec.full_x      = full_x;
    spec.full_y      = full_y;
    spec.full_z      = full_z;
    spec.full_width  = full_width;
    spec.full_height = full_height;
    spec.full_depth  = full_depth;
}

void
imagespec_set_tile_size(ImageSpec& spec, int width, int height, int depth)
{
    spec.tile_width  = width;
    spec.tile_height = height;
    spec.tile_depth  = depth;
}

void
imagespec_set_channel_names(ImageSpec& spec,
                            const rust::Vec<rust::String>& names)
{
    spec.channelnames.clear();
    spec.channelnames.reserve(names.size());
    for (const rust::String& name : names)
        spec.channelnames.emplace_back(name.data(), name.size());
}

void
imagespec_set_channelformats(ImageSpec& spec,
                             rust::Slice<const TypeDesc> formats)
{
    // Assign the field directly, and never route through or after
    // ImageSpec::set_format, which clears channelformats.
    spec.channelformats.assign(formats.begin(), formats.end());
}

void
imagespec_set_alpha_channel(ImageSpec& spec, int index)
{
    spec.alpha_channel = index;
}

void
imagespec_set_z_channel(ImageSpec& spec, int index)
{
    spec.z_channel = index;
}

void
imagespec_set_deep(ImageSpec& spec, bool deep)
{
    spec.deep = deep;
}

void
imagespec_attribute_int(ImageSpec& spec, const rust::Str name, int value)
{
    spec.attribute(to_string_view(name), value);
}

void
imagespec_attribute_float(ImageSpec& spec, const rust::Str name, float value)
{
    spec.attribute(to_string_view(name), value);
}

void
imagespec_attribute_string(ImageSpec& spec, const rust::Str name,
                           const rust::Str value)
{
    spec.attribute(to_string_view(name), to_string_view(value));
}

bool
imagespec_erase_attribute(ImageSpec& spec, const rust::Str name)
{
    const std::size_t before = spec.extra_attribs.size();
    spec.erase_attribute(std::string(name.data(), name.size()));
    return spec.extra_attribs.size() != before;
}

bool
imagespec_has_attribute(const ImageSpec& spec, const rust::Str name)
{
    return spec.find_attribute(to_string_view(name)) != nullptr;
}

TypeDesc
imagespec_attribute_type(const ImageSpec& spec, const rust::Str name)
{
    return spec.getattributetype(to_string_view(name));
}

int
imagespec_get_int_attribute(const ImageSpec& spec, const rust::Str name,
                            int defaultval)
{
    return spec.get_int_attribute(to_string_view(name), defaultval);
}

float
imagespec_get_float_attribute(const ImageSpec& spec, const rust::Str name,
                              float defaultval)
{
    return spec.get_float_attribute(to_string_view(name), defaultval);
}

rust::String
imagespec_get_string_attribute(const ImageSpec& spec, const rust::Str name,
                               const rust::Str defaultval)
{
    const OIIO::string_view value
        = spec.get_string_attribute(to_string_view(name),
                                    to_string_view(defaultval));
    // Metadata is arbitrary file content, so never assume it is valid UTF-8.
    return rust::String::lossy(value.data(), value.size());
}

rust::String
imagespec_attribute_to_string(const ImageSpec& spec, const rust::Str name)
{
    const OIIO::ParamValue* attribute = spec.find_attribute(
        to_string_view(name));
    if (attribute == nullptr)
        return rust::String();
    const std::string value = attribute->get_string();
    return rust::String::lossy(value.data(), value.size());
}

rust::Vec<uint8_t>
imagespec_attribute_bytes(const ImageSpec& spec, const rust::Str name)
{
    rust::Vec<uint8_t> bytes;
    const OIIO::ParamValue* attribute = spec.find_attribute(
        to_string_view(name));
    if (attribute == nullptr)
        return bytes;

    const int size = attribute->datasize();
    if (size <= 0)
        return bytes;
    const auto* data = static_cast<const uint8_t*>(attribute->data());
    if (data == nullptr)
        return bytes;

    bytes.reserve(std::size_t(size));
    for (int i = 0; i < size; ++i)
        bytes.push_back(data[i]);
    return bytes;
}

bool
attribute_bytes_are_writable(const rust::Str type_name, size_t length)
{
    const OIIO::TypeDesc type(std::string(type_name.data(), type_name.size()));
    if (type == OIIO::TypeUnknown)
        return false;
    // An array whose length is not concrete defeats every check below.
    // TypeDesc::fromstring presets arraylen to -1, so "float[]" parses to -1
    // and "uint8[-3]" to -3, while TypeDesc::size() clamps the count to at
    // least one -- so "float[]" measures four bytes and a four byte payload
    // would sail through. The clamp is not applied on the way back out: both
    // sprint_type and format_type size their loop as `arraylen ? arraylen : 1`
    // with the raw value, and size_t(-1) walks off the end of the stored value.
    if (type.arraylen < 0)
        return false;
    // The value must be exactly the size the type describes, or OpenImageIO
    // would read past what was handed to it.
    if (type.size() != length)
        return false;
    if (type.basetype == OIIO::TypeDesc::STRING)
        return false;
    // A pointer or a hashed string carries a raw process address, which is
    // meaningless in another process and would be written into the file.
    if (type.basetype == OIIO::TypeDesc::PTR
        || type.basetype == OIIO::TypeDesc::USTRINGHASH)
        return false;
    return true;
}

bool
imagespec_attribute_set_bytes(ImageSpec& spec, const rust::Str name,
                              const rust::Str type_name,
                              rust::Slice<const uint8_t> bytes)
{
    if (!attribute_bytes_are_writable(type_name, bytes.size()))
        return false;
    const OIIO::TypeDesc type(std::string(type_name.data(), type_name.size()));
    if (type == OIIO::TypeUnknown)
        return false;
    spec.attribute(to_string_view(name), type, bytes.data());
    return true;
}

rust::Vec<rust::String>
imagespec_attribute_strings(const ImageSpec& spec, const rust::Str name)
{
    rust::Vec<rust::String> values;
    const OIIO::ParamValue* attribute = spec.find_attribute(
        to_string_view(name));
    if (attribute == nullptr || attribute->type().basetype != OIIO::TypeDesc::STRING)
        return values;

    const int count = attribute->type().basevalues();
    const auto* strings = static_cast<const OIIO::ustring*>(attribute->data());
    if (strings == nullptr)
        return values;
    for (int i = 0; i < count; ++i) {
        const OIIO::string_view text = strings[i];
        values.push_back(rust::String::lossy(text.data(), text.size()));
    }
    return values;
}

bool
imagespec_attribute_set_strings(ImageSpec& spec, const rust::Str name,
                                const rust::Str type_name,
                                const rust::Vec<rust::String>& values)
{
    const OIIO::TypeDesc type(std::string(type_name.data(), type_name.size()));
    if (type == OIIO::TypeUnknown || type.basetype != OIIO::TypeDesc::STRING)
        return false;
    if (std::size_t(type.basevalues()) != values.size())
        return false;

    // ustrings live for the life of the process, so the pointers handed to
    // OpenImageIO stay valid after this vector goes away.
    std::vector<OIIO::ustring> interned;
    interned.reserve(values.size());
    for (const rust::String& value : values)
        interned.emplace_back(value.data(), value.size());

    spec.attribute(to_string_view(name), type, interned.data());
    return true;
}

std::unique_ptr<std::vector<ImageSpec>>
imagespec_vector_new()
{
    return std::make_unique<std::vector<ImageSpec>>();
}

void
imagespec_vector_push(std::vector<ImageSpec>& specs, const ImageSpec& spec)
{
    specs.push_back(spec);
}

rust::Vec<rust::String>
imagespec_attribute_names(const ImageSpec& spec)
{
    rust::Vec<rust::String> names;
    for (const OIIO::ParamValue& attribute : spec.extra_attribs) {
        const OIIO::string_view name = attribute.name();
        names.push_back(rust::String::lossy(name.data(), name.size()));
    }
    return names;
}
#pragma endregion

#pragma region ImageInput
std::unique_ptr<ImageInput>
imageinput_open_with_config(const rust::Str filename, const ImageSpec& config)
{
    std::unique_ptr<OIIO::ImageInput> image_input(
        OIIO::ImageInput::open(std::string(filename), &config));

    if (image_input) {
        return image_input;
    } else {
        throw std::runtime_error(OIIO::geterror());
    }
}

std::unique_ptr<ImageInput>
imageinput_open_without_config(const rust::Str filename)
{
    std::unique_ptr<OIIO::ImageInput> image_input(
        OIIO::ImageInput::open(std::string(filename), nullptr));

    return image_input;
}

std::unique_ptr<ImageInput>
imageinput_create_with_config(const rust::Str filename, bool do_open,
                              const ImageSpec& config,
                              const rust::Str plugin_searchpath)
{
    OIIO::string_view c_plugin_searchpath(plugin_searchpath.data(),
                                          plugin_searchpath.size());
    std::unique_ptr<OIIO::ImageInput> image_input(
        OIIO::ImageInput::create(std::string(filename), do_open, &config,
                                  nullptr, c_plugin_searchpath));

    if (image_input) {
        return image_input;
    } else {
        throw std::runtime_error(OIIO::geterror());
    }
}

std::unique_ptr<ImageInput>
imageinput_create_without_config(const rust::Str filename, bool do_open,
                                 const rust::Str plugin_searchpath)
{
    OIIO::string_view c_plugin_searchpath(plugin_searchpath.data(),
                                          plugin_searchpath.size());
    std::unique_ptr<OIIO::ImageInput> image_input(
        OIIO::ImageInput::create(std::string(filename), do_open, nullptr,
                                  nullptr, c_plugin_searchpath));

    if (image_input) {
        return image_input;
    } else {
        throw std::runtime_error(OIIO::geterror());
    }
}

rust::Str
imageinput_format_name(const ImageInput& imageinput)
{
    return rust::Str(imageinput.format_name());
}

bool
imageinput_supports(const ImageInput& imageinput, const rust::Str feature)
{
    return imageinput.supports(
        OIIO::string_view(feature.data(), feature.size()));
}

bool
imageinput_valid_file(const ImageInput& imageinput, const rust::Str filename)
{
    // The base ImageInput::valid_file const_casts `this` and, for plugins
    // without an override, re-opens and closes the receiver on the probe
    // file — silently closing the caller's live reader and resetting its
    // I/O proxy. Probe with a throwaway instance of the same plugin
    // instead, so the caller's reader is never touched.
    std::unique_ptr<ImageInput> probe
        = ImageInput::create(imageinput.format_name());
    if (!probe)
        return false;
    return probe->valid_file(std::string(filename));
}

const ImageSpec&
imageinput_spec(const OIIO::ImageInput& imageinput)
{
    return imageinput.spec();
}

std::unique_ptr<ImageSpec>
imageinput_spec_subimage_miplevel(OIIO::ImageInput& imageinput,
                                  int32_t subimage, int32_t miplevel)
{
    return std::make_unique<ImageSpec>(imageinput.spec(subimage, miplevel));
}

std::unique_ptr<ImageSpec>
imageinput_spec_dimensions(OIIO::ImageInput& imageinput, int32_t subimage,
                           int32_t miplevel)
{
    return std::make_unique<ImageSpec>(
        imageinput.spec_dimensions(subimage, miplevel));
}

std::unique_ptr<ImageInput>
imageinput_open_with_ioproxy(const rust::Str filename, IOProxy* ioproxy)
{
    return OIIO::ImageInput::open(std::string(filename), nullptr, ioproxy);
}

bool
imageinput_close(ImageInput& imageinput)
{
    return imageinput.close();
}

int
imageinput_current_subimage(const ImageInput& imageinput)
{
    return imageinput.current_subimage();
}

int
imageinput_current_miplevel(const ImageInput& imageinput)
{
    return imageinput.current_miplevel();
}

bool
imageinput_seek_subimage(ImageInput& imageinput, int subimage, int miplevel)
{
    return imageinput.seek_subimage(subimage, miplevel);
}

bool
imageinput_read_scanline(ImageInput& imageinput, int y, int z, TypeDesc format,
                         rust::Slice<uint8_t> data, int64_t xstride)
{
    return imageinput.read_scanline(y, z, format, data.data(), xstride);
}

bool
imageinput_read_scanlines(ImageInput& imageinput, int subimage, int miplevel,
                          int ybegin, int yend, int z, int chbegin, int chend,
                          TypeDesc format, rust::Slice<uint8_t> data,
                          int64_t xstride, int64_t ystride)
{
    return imageinput.read_scanlines(subimage, miplevel, ybegin, yend, z,
                                     chbegin, chend, format, data.data(),
                                     xstride, ystride);
}

bool
imageinput_read_image(ImageInput& imageinput, int subimage, int miplevel,
                      int chbegin, int chend, TypeDesc format,
                      rust::Slice<uint8_t> data, int64_t xstride,
                      int64_t ystride, int64_t zstride)
{
    return imageinput.read_image(subimage, miplevel, chbegin, chend, format,
                                 data.data(), xstride, ystride, zstride);
}

bool
imageinput_read_image_span(ImageInput& imageinput, int subimage, int miplevel,
                           int chbegin, int chend, TypeDesc format,
                           rust::Slice<uint8_t> data)
{
    const ImageSpec spec = imageinput.spec_dimensions(subimage, miplevel);
    if (chend < 0 || chend > spec.nchannels)
        chend = spec.nchannels;

    detail::PixelLayout layout;
    if (!imagespec_valid(spec) || chbegin < 0 || chbegin >= chend
        || !detail::bounded_pixel_layout(
            static_cast<int64_t>(chend) - chbegin, spec.width, spec.height,
            spec.depth, format, data.size(), layout)) {
        imageinput.errorfmt("invalid dimensions or destination buffer for bounded image read");
        return false;
    }

    // The layout above is the safety contract: the buffer holds exactly one
    // contiguous value per channel, pixel, row, and slice, and its byte size
    // was checked against those dimensions.
    //
    // The strides are then passed explicitly instead of through OpenImageIO's
    // `image_span` overload. That overload forwarded the x and y ranges to
    // the pointer version in the wrong order and dropped ystride and zstride,
    // so a tiled read returned a different rectangle of the image -- usually
    // reporting success, and for some shapes leaving half the destination
    // untouched. Reported as OpenImageIO issue #5400 and fixed upstream in
    // PR #5531, first released in 3.1.18.1 and 3.2.1.1.
    //
    // The explicit-stride overload is correct on every version, including
    // those predating the fix, so it stays until the crate's minimum rises
    // above the affected range.
    return imageinput.read_image(subimage, miplevel, chbegin, chend, format,
                                 data.data(), layout.x_stride, layout.y_stride,
                                 layout.z_stride);
}

namespace {
// Shared front half of the bounded partial reads: resolve the level's
// dimensions and normalise the channel range.
inline bool
bounded_read_setup(ImageInput& imageinput, int subimage, int miplevel,
                   int chbegin, int& chend, ImageSpec& spec)
{
    spec = imageinput.spec_dimensions(subimage, miplevel);
    if (chend < 0 || chend > spec.nchannels)
        chend = spec.nchannels;
    return imagespec_valid(spec) && chbegin >= 0 && chbegin < chend;
}
}  // namespace

bool
imageinput_read_scanlines_span(ImageInput& imageinput, int subimage,
                               int miplevel, int ybegin, int yend, int z,
                               int chbegin, int chend, TypeDesc format,
                               rust::Slice<uint8_t> data)
{
    ImageSpec spec;
    detail::PixelLayout layout;
    if (!bounded_read_setup(imageinput, subimage, miplevel, chbegin, chend,
                            spec)
        || ybegin >= yend || ybegin < spec.y
        || yend > static_cast<int64_t>(spec.y) + spec.height || z < spec.z
        || z >= static_cast<int64_t>(spec.z) + spec.depth
        || !detail::bounded_pixel_layout(static_cast<int64_t>(chend) - chbegin,
                                         spec.width,
                                         static_cast<int64_t>(yend) - ybegin, 1,
                                         format, data.size(), layout)) {
        imageinput.errorfmt(
            "invalid scanline range or destination buffer for bounded read");
        return false;
    }

    return imageinput.read_scanlines(subimage, miplevel, ybegin, yend, z,
                                     chbegin, chend, format, data.data(),
                                     layout.x_stride, layout.y_stride);
}

bool
imageinput_read_tiles_span(ImageInput& imageinput, int subimage, int miplevel,
                           int xbegin, int xend, int ybegin, int yend,
                           int zbegin, int zend, int chbegin, int chend,
                           TypeDesc format, rust::Slice<uint8_t> data)
{
    ImageSpec spec;
    detail::PixelLayout layout;
    if (!bounded_read_setup(imageinput, subimage, miplevel, chbegin, chend,
                            spec)
        || spec.tile_width <= 0 || xbegin >= xend || ybegin >= yend
        || zbegin >= zend || xbegin < spec.x
        || xend > static_cast<int64_t>(spec.x) + spec.width || ybegin < spec.y
        || yend > static_cast<int64_t>(spec.y) + spec.height || zbegin < spec.z
        || zend > static_cast<int64_t>(spec.z) + spec.depth
        || !detail::bounded_pixel_layout(static_cast<int64_t>(chend) - chbegin,
                                         static_cast<int64_t>(xend) - xbegin,
                                         static_cast<int64_t>(yend) - ybegin,
                                         static_cast<int64_t>(zend) - zbegin,
                                         format, data.size(), layout)) {
        imageinput.errorfmt(
            "invalid tile range or destination buffer for bounded read");
        return false;
    }

    return imageinput.read_tiles(subimage, miplevel, xbegin, xend, ybegin, yend,
                                 zbegin, zend, chbegin, chend, format,
                                 data.data(), layout.x_stride, layout.y_stride,
                                 layout.z_stride);
}

// The three deep read paths below are the one place in this translation unit
// where OpenImageIO sizes an allocation from the FILE rather than from a
// buffer the caller already validated. The reader fills the `DeepData` from
// the sample counts in the header, and `DeepData::init` resizes three
// per-pixel vectors with no try/catch of its own, so a file claiming more
// samples than the machine can hold throws `std::bad_alloc` or
// `std::length_error` straight out of the reader.
//
// That is the same mechanism `imagebuf_new_from_spec_checked` guards in
// `ffi_imagebuf.cpp`, reached by a different route. cxx wraps these shims
// `noexcept`, so an escaping exception is `std::terminate`: a malformed or
// hostile file would abort the process instead of returning an error. Every
// other read path here hands OpenImageIO a caller-sized buffer and is bounded
// by it, and the format readers catch their own exceptions, so the boundary
// belongs here rather than on all sixty-odd shims.
//
// `catch (...)` is deliberate. OpenEXR raises `Iex::BaseExc`, which derives
// from `std::exception`, but the readers are reached through a plugin
// boundary and the point of a boundary is to hold regardless of what arrives.
template<typename Body>
static bool
guard_deep_read(rust::String& error, const char* what, Body&& body)
{
    error = rust::String();
    try {
        return body();
    } catch (const std::exception& exception) {
        const std::string recorded = exception.what();
        error = rust::String::lossy(
            recorded.empty()
                ? std::string(what) + ": OpenImageIO could not allocate the "
                                      "deep samples this file declares"
                : std::string(what) + ": " + recorded);
        return false;
    } catch (...) {
        error = rust::String::lossy(
            std::string(what)
            + ": OpenImageIO raised an unrecognised exception");
        return false;
    }
}

bool
imageinput_read_native_deep_scanlines(ImageInput& imageinput, int subimage,
                                      int miplevel, int ybegin, int yend, int z,
                                      int chbegin, int chend, DeepData& data,
                                      rust::String& error)
{
    return guard_deep_read(error, "read deep scanlines", [&] {
        return imageinput.read_native_deep_scanlines(subimage, miplevel, ybegin,
                                                     yend, z, chbegin, chend,
                                                     data);
    });
}

bool
imageinput_read_native_deep_tiles(ImageInput& imageinput, int subimage,
                                  int miplevel, int xbegin, int xend,
                                  int ybegin, int yend, int zbegin, int zend,
                                  int chbegin, int chend, DeepData& data,
                                  rust::String& error)
{
    return guard_deep_read(error, "read deep tiles", [&] {
        return imageinput.read_native_deep_tiles(subimage, miplevel, xbegin,
                                                 xend, ybegin, yend, zbegin,
                                                 zend, chbegin, chend, data);
    });
}

bool
imageinput_read_native_deep_image(ImageInput& imageinput, int subimage,
                                  int miplevel, DeepData& data,
                                  rust::String& error)
{
    return guard_deep_read(error, "read deep image", [&] {
        return imageinput.read_native_deep_image(subimage, miplevel, data);
    });
}

bool
imageinput_read_native_scanline(ImageInput& imageinput, int subimage,
                                int miplevel, int y, int z,
                                rust::Slice<uint8_t> data)
{
    return imageinput.read_native_scanline(subimage, miplevel, y, z,
                                           data.data());
}

bool
imageinput_read_native_scanlines(ImageInput& imageinput, int subimage,
                                 int miplevel, int ybegin, int yend, int z,
                                 int chbegin, int chend,
                                 rust::Slice<uint8_t> data)
{
    return imageinput.read_native_scanlines(subimage, miplevel, ybegin, yend, z,
                                            chbegin, chend, data.data());
}

bool
imageinput_read_native_tile(ImageInput& imageinput, int subimage, int miplevel,
                            int x, int y, int z, rust::Slice<uint8_t> data)
{
    return imageinput.read_native_tile(subimage, miplevel, x, y, z,
                                       data.data());
}

bool
imageinput_read_native_tiles(ImageInput& imageinput, int xbegin, int xend,
                             int ybegin, int yend, int zbegin, int zend,
                             int chbegin, int chend, rust::Slice<uint8_t> data)
{
    const int subimage = imageinput.current_subimage();
    const int miplevel = imageinput.current_miplevel();
    const ImageSpec dimensions
        = imageinput.spec_dimensions(subimage, miplevel);
    OIIO::span<std::byte> c_data(reinterpret_cast<std::byte*>(data.data()),
                                 data.size());

    if (dimensions.depth > 1) {
        return imageinput.read_native_volumetric_tiles(
            subimage, miplevel, xbegin, xend, ybegin, yend, zbegin, zend,
            chbegin, chend, c_data);
    }

    if (zbegin != dimensions.z || zend != dimensions.z + 1) {
        return false;
    }

    return imageinput.read_native_tiles(subimage, miplevel, xbegin, xend,
                                        ybegin, yend, chbegin, chend, c_data);
}

bool
imageinput_set_ioproxy(ImageInput& imageinput, IOProxy* ioproxy)
{
    return imageinput.set_ioproxy(ioproxy);
}

bool
imageinput_has_error(const ImageInput& imageinput)
{
    return imageinput.has_error();
}

rust::String
imageinput_geterror(ImageInput& imageinput)
{
// OpenImageIO builds its error text from the file: a damaged EXR whose
// attribute name is arbitrary bytes comes back quoted verbatim. cxx's
// throwing rust::String constructor would turn that into std::terminate,
// because the shim it is called from is noexcept. Never assume UTF-8.
    return rust::String::lossy(imageinput.geterror());
}

void
imageinput_seterror(ImageInput& imageinput, const rust::Str message)
{
    // Two things are wrong with passing message.data() here. A rust::Str is a
    // pointer and a length over a Rust &str and carries no NUL, so errorfmt
    // scans past the end of any string that is a prefix of a larger one. And
    // errorfmt with no arguments is still a runtime format call, so a "{}"
    // anywhere in the caller's text throws fmt::format_error out of a shim
    // that cxx declares noexcept, which is std::terminate. Passing the text as
    // an argument to a fixed format string settles both.
    imageinput.errorfmt("{}", to_string_view(message));
}

void
imageinput_set_threads(ImageInput& imageinput, int n)
{
    return imageinput.threads(n);
}

int
imageinput_threads(const ImageInput& imageinput)
{
    return imageinput.threads();
}
#pragma endregion

#pragma region ImageOutput
std::unique_ptr<ImageOutput>
imageoutput_create(const rust::Str filename, IOProxy* ioproxy,
                   const rust::Str plugin_searchpath)
{
    OIIO::string_view c_filename(filename.data(), filename.size());
    OIIO::string_view c_plugin_searchpath(plugin_searchpath.data(),
                                          plugin_searchpath.size());
    return ImageOutput::create(c_filename, ioproxy, c_plugin_searchpath);
}

rust::Str
imageoutput_format_name(const ImageOutput& imageoutput)
{
    return imageoutput.format_name();
}

int
imageoutput_supports(const ImageOutput& imageoutput, const rust::Str feature)
{
    return imageoutput.supports(
        OIIO::string_view(feature.data(), feature.size()));
}

bool
imageoutput_open(ImageOutput& imageoutput, const rust::Str filename,
                 const ImageSpec& newspec, OpenMode mode)
{
    return imageoutput.open(std::string(filename), newspec, mode);
}

bool
imageoutput_open_multi_subimage(ImageOutput& imageoutput,
                                const rust::Str filename, int subimages,
                                const ImageSpec* specs)
{
    return imageoutput.open(std::string(filename), subimages, specs);
}

bool
imageoutput_open_specs(ImageOutput& imageoutput, const rust::Str filename,
                       const std::vector<ImageSpec>& specs)
{
    if (specs.empty()
        || specs.size() > static_cast<std::size_t>(
               std::numeric_limits<int>::max())) {
        imageoutput.errorfmt("invalid subimage count for a multi-part write");
        return false;
    }
    return imageoutput.open(std::string(filename),
                            static_cast<int>(specs.size()), specs.data());
}

const ImageSpec&
imageoutput_spec(const ImageOutput& imageoutput)
{
    return imageoutput.spec();
}

bool
imageoutput_close(ImageOutput& imageoutput)
{
    return imageoutput.close();
}

bool
imageoutput_write_scanline(ImageOutput& imageoutput, int y, int z,
                           TypeDesc format, const rust::Slice<uint8_t> data,
                           int64_t xstride)
{
    return imageoutput.write_scanline(y, z, format, data.data(), xstride);
}

bool
imageoutput_write_scanlines(ImageOutput& imageoutput, int ybegin, int yend,
                            int z, TypeDesc format,
                            const rust::Slice<uint8_t> data, int64_t xstride,
                            int64_t ystride)
{
    return imageoutput.write_scanlines(ybegin, yend, z, format, data.data(),
                                       xstride, ystride);
}

bool
imageoutput_write_tile(ImageOutput& imageoutput, int x, int y, int z,
                       TypeDesc format, const rust::Slice<uint8_t> data,
                       int64_t xstride, int64_t ystride, int64_t zstride)
{
    return imageoutput.write_tile(x, y, z, format, data.data(), xstride,
                                  ystride, zstride);
}

bool
imageoutput_write_tiles(ImageOutput& imageoutput, int xbegin, int xend,
                        int ybegin, int yend, int zbegin, int zend,
                        TypeDesc format, const rust::Slice<uint8_t> data,
                        int64_t xstride, int64_t ystride, int64_t zstride)
{
    return imageoutput.write_tiles(xbegin, xend, ybegin, yend, zbegin, zend,
                                   format, data.data(), xstride, ystride,
                                   zstride);
}

bool
imageoutput_write_rectangle(ImageOutput& imageoutput, int xbegin, int xend,
                            int ybegin, int yend, int zbegin, int zend,
                            TypeDesc format, const rust::Slice<uint8_t> data,
                            int64_t xstride, int64_t ystride, int64_t zstride)
{
    return imageoutput.write_rectangle(xbegin, xend, ybegin, yend, zbegin, zend,
                                       format, data.data(), xstride, ystride,
                                       zstride);
}

bool
imageoutput_write_image(ImageOutput& imageoutput, TypeDesc format,
                        const rust::Slice<uint8_t> data, int64_t xstride,
                        int64_t ystride, int64_t zstride)
{
    return imageoutput.write_image(format, data.data(), xstride, ystride,
                                   zstride);
}

bool
imageoutput_write_image_span(ImageOutput& imageoutput, TypeDesc format,
                             const rust::Slice<const uint8_t> data)
{
    const ImageSpec& spec = imageoutput.spec();

    detail::PixelLayout layout;
    if (!imagespec_valid(spec)
        || !detail::bounded_pixel_layout(spec.nchannels, spec.width,
                                         spec.height, spec.depth, format,
                                         data.size(), layout)) {
        imageoutput.errorfmt(
            "invalid dimensions or source buffer for bounded image write");
        return false;
    }

    // Explicit strides rather than OpenImageIO's `image_span` overload; see
    // the note in imageinput_read_image_span.
    return imageoutput.write_image(format, data.data(), layout.x_stride,
                                   layout.y_stride, layout.z_stride);
}

bool
imageoutput_write_scanlines_span(ImageOutput& imageoutput, int ybegin, int yend,
                                 TypeDesc format,
                                 const rust::Slice<const uint8_t> data)
{
    const ImageSpec& spec = imageoutput.spec();

    detail::PixelLayout layout;
    if (!imagespec_valid(spec) || ybegin < spec.y
        || yend > static_cast<int64_t>(spec.y) + spec.height || ybegin >= yend
        || !detail::bounded_pixel_layout(spec.nchannels, spec.width,
                                         static_cast<int64_t>(yend) - ybegin, 1,
                                         format, data.size(), layout)) {
        imageoutput.errorfmt(
            "invalid scanline range or source buffer for bounded write");
        return false;
    }

    // The `image_span` overload of write_scanlines validated the range against
    // [0, height) rather than [y, y + height), so it rejected ranges expressed
    // in image coordinates whenever the data window origin was non-zero
    // ("Invalid scanline range"). Fixed upstream in PR #5531 alongside the
    // read_tiles transposition, first released in 3.1.18.1 and 3.2.1.1; the
    // explicit-stride overload is used here because it is correct on every
    // version.
    return imageoutput.write_scanlines(ybegin, yend, spec.z, format,
                                       data.data(), layout.x_stride,
                                       layout.y_stride);
}

bool
imageoutput_write_tiles_span(ImageOutput& imageoutput, int xbegin, int xend,
                             int ybegin, int yend, int zbegin, int zend,
                             TypeDesc format,
                             const rust::Slice<const uint8_t> data)
{
    const ImageSpec& spec = imageoutput.spec();

    detail::PixelLayout layout;
    if (!imagespec_valid(spec) || spec.tile_width <= 0 || xbegin >= xend
        || ybegin >= yend || zbegin >= zend || xbegin < spec.x
        || xend > static_cast<int64_t>(spec.x) + spec.width || ybegin < spec.y
        || yend > static_cast<int64_t>(spec.y) + spec.height || zbegin < spec.z
        || zend > static_cast<int64_t>(spec.z) + spec.depth
        || !detail::bounded_pixel_layout(spec.nchannels,
                                         static_cast<int64_t>(xend) - xbegin,
                                         static_cast<int64_t>(yend) - ybegin,
                                         static_cast<int64_t>(zend) - zbegin,
                                         format, data.size(), layout)) {
        imageoutput.errorfmt(
            "invalid tile range or source buffer for bounded write");
        return false;
    }

    return imageoutput.write_tiles(xbegin, xend, ybegin, yend, zbegin, zend,
                                   format, data.data(), layout.x_stride,
                                   layout.y_stride, layout.z_stride);
}

bool
imageoutput_write_rectangle_span(ImageOutput& imageoutput, int xbegin, int xend,
                                 int ybegin, int yend, int zbegin, int zend,
                                 TypeDesc format,
                                 const rust::Slice<const uint8_t> data)
{
    const ImageSpec& spec = imageoutput.spec();

    detail::PixelLayout layout;
    if (!imagespec_valid(spec) || xbegin >= xend || ybegin >= yend
        || zbegin >= zend || xbegin < spec.x
        || xend > static_cast<int64_t>(spec.x) + spec.width || ybegin < spec.y
        || yend > static_cast<int64_t>(spec.y) + spec.height || zbegin < spec.z
        || zend > static_cast<int64_t>(spec.z) + spec.depth
        || !detail::bounded_pixel_layout(spec.nchannels,
                                         static_cast<int64_t>(xend) - xbegin,
                                         static_cast<int64_t>(yend) - ybegin,
                                         static_cast<int64_t>(zend) - zbegin,
                                         format, data.size(), layout)) {
        imageoutput.errorfmt(
            "invalid rectangle range or source buffer for bounded write");
        return false;
    }

    return imageoutput.write_rectangle(xbegin, xend, ybegin, yend, zbegin,
                                       zend, format, data.data(),
                                       layout.x_stride, layout.y_stride,
                                       layout.z_stride);
}

bool
imageinput_read_native_image_bytes(ImageInput& imageinput, int subimage,
                                   int miplevel, rust::Slice<uint8_t> data,
                                   rust::String& error)
{
    error = rust::String();
    const ImageSpec spec = imageinput.spec(subimage, miplevel);
    if (spec.format.basetype == OIIO::TypeDesc::UNKNOWN || spec.width <= 0
        || spec.height <= 0 || spec.depth <= 0 || spec.nchannels <= 0) {
        error = rust::String::lossy(
            "read native image: the subimage or mip level does not exist");
        return false;
    }
    if (spec.deep) {
        error = rust::String::lossy(
            "read native image: deep images hold samples, not pixels; use "
            "the deep reading API");
        return false;
    }

    const uint64_t pixel_bytes = spec.pixel_bytes(true);
    const uint64_t pixels      = spec.image_pixels();
    if (pixel_bytes == 0 || pixels == 0
        || pixels > std::numeric_limits<uint64_t>::max() / pixel_bytes
        || uint64_t(data.size()) != pixels * pixel_bytes) {
        error = rust::String::lossy(OIIO::Strutil::fmt::format(
            "read native image: the buffer holds {} bytes and the image "
            "needs {}",
            data.size(), pixels * pixel_bytes));
        return false;
    }

    imageinput.geterror(true);
    if (!imageinput.read_image(subimage, miplevel, 0, -1,
                               OIIO::TypeDesc::UNKNOWN, data.data())) {
        std::string message = imageinput.geterror(true);
        if (message.empty())
            message = "OpenImageIO could not read the image";
        error = rust::String::lossy(message);
        return false;
    }
    return true;
}

bool
imageoutput_write_deep_scanlines(ImageOutput& imageoutput, int ybegin, int yend,
                                 int z, const DeepData& deepdata)
{
    return imageoutput.write_deep_scanlines(ybegin, yend, z, deepdata);
}

bool
imageoutput_write_deep_tiles(ImageOutput& imageoutput, int xbegin, int xend,
                             int ybegin, int yend, int zbegin, int zend,
                             const DeepData& deepdata)
{
    return imageoutput.write_deep_tiles(xbegin, xend, ybegin, yend, zbegin,
                                        zend, deepdata);
}

bool
imageoutput_write_deep_image(ImageOutput& imageoutput, const DeepData& deepdata)
{
    return imageoutput.write_deep_image(deepdata);
}

bool
imageoutput_set_thumbnail(ImageOutput& imageoutput, const ImageBuf& thumb)
{
    return imageoutput.set_thumbnail(thumb);
}

bool
imageoutput_copy_image(ImageOutput& imageoutput, ImageInput* imageinput)
{
    return imageoutput.copy_image(imageinput);
}

bool
imageoutput_set_ioproxy(ImageOutput& imageoutput, IOProxy* ioproxy)
{
    return imageoutput.set_ioproxy(ioproxy);
}

bool
imageoutput_has_error(const ImageOutput& imageoutput)
{
    return imageoutput.has_error();
}

rust::String
imageoutput_geterror(const ImageOutput& imageoutput, bool clear)
{
// OpenImageIO builds its error text from the file: a damaged EXR whose
// attribute name is arbitrary bytes comes back quoted verbatim. cxx's
// throwing rust::String constructor would turn that into std::terminate,
// because the shim it is called from is noexcept. Never assume UTF-8.
    return rust::String::lossy(imageoutput.geterror(clear));
}

void
imageoutput_seterror(ImageOutput& imageoutput, const rust::Str message)
{
    // See imageinput_seterror.
    imageoutput.errorfmt("{}", to_string_view(message));
}

void
imageoutput_set_threads(ImageOutput& imageoutput, int n)
{
    imageoutput.threads(n);
}

int
imageoutput_threads(const ImageOutput& imageoutput)
{
    return imageoutput.threads();
}
#pragma endregion

#pragma region Utility Functions
void
shutdown()
{
    OIIO::shutdown();
}

int
openimageio_version()
{
    return OIIO::openimageio_version();
}

int
openimageio_build_version()
{
    return OIIO_VERSION;
}

bool
has_error()
{
    return OIIO::has_error();
}

rust::String
get_error(bool clear)
{
    // Returning the std::string directly would convert through cxx's throwing
    // constructor, and this shim is noexcept, so a message OpenImageIO built
    // out of bytes taken from the file would be std::terminate rather than an
    // error. Every constructor called from these shims must be the lossy one.
    const std::string error = OIIO::geterror(clear);
    return rust::String::lossy(error.data(), error.size());
}

bool
attribute(const rust::Str name, TypeDesc type, rust::Slice<uint8_t> value)
{
    return OIIO::attribute(std::string_view(name.data(), name.length()), type,
                           value.data());
}

bool
attribute_float(const rust::Str name, float value)
{
    return OIIO::attribute(std::string_view(name.data(), name.length()), value);
}

bool
attribute_int(const rust::Str name, const int value)
{
    return OIIO::attribute(std::string_view(name.data(), name.length()), value);
}

bool
attribute_string(const rust::Str name, const rust::Str value)
{
    // OIIO's string overload wants a TypeString and the address of a C string,
    // so the value has to be null-terminated and must outlive the call. A
    // rust::Str is neither owned nor terminated, hence the copy.
    const std::string owned(value.data(), value.length());
    const char* pointer = owned.c_str();
    return OIIO::attribute(std::string_view(name.data(), name.length()),
                           OIIO::TypeString, &pointer);
}

bool
getattribute(const rust::Str name, const TypeDesc type,
             rust::Slice<uint8_t> value)
{
    return OIIO::getattribute(std::string_view(name.data(), name.length()),
                              type, value.data());
}

bool
getattribute_int(const rust::Str name, int& value)
{
    return OIIO::getattribute(std::string_view(name.data(), name.length()),
                              value);
}

bool
getattribute_float(const rust::Str name, float& value)
{
    {
        return OIIO::getattribute(std::string_view(name.data(), name.length()),
                                  value);
    }
}

bool
getattribute_string(const rust::Str name, rust::String& value)
{
    std::string c_value;
    bool result
        = OIIO::getattribute(std::string_view(name.data(), name.length()),
                             c_value);
    value = rust::String::lossy(c_value);
    return result;
}

int
get_int_attribute(const rust::Str name, int defaultval)
{
    return OIIO::get_int_attribute(std::string_view(name.data(), name.length()),
                                   defaultval);
}

float
get_float_attribute(const rust::Str name, float defaultval)
{
    return OIIO::get_float_attribute(std::string_view(name.data(),
                                                      name.length()),
                                     defaultval);
}

rust::String
get_string_attribute(const rust::Str name, const rust::Str defaultval)
{
    std::string c_defaultval(defaultval.data(), defaultval.length());
    std::string c_value = OIIO::get_string_attribute(
        std::string_view(name.data(), name.length()), c_defaultval);
    return rust::String::lossy(c_value);
}

// void
// declare_imageio_format(const rust::Str name,
//                        rust::Fn<ImageInput*(ImageInput*)> input_creator,
//                        const rust::Slice<const rust::Str> input_extensions,
//                        rust::Fn<ImageOutput*(ImageOutput*)> output_creator,
//                        const rust::Slice<const rust::Str> output_extensions,
//                        const rust::Str lib_version)
// {
//     auto c_input_creator = [&](OIIO::ImageInput*) -> OIIO::ImageInput* {
//         return input_creator();
//     };

//     std::vector<const char*> c_input_extensions;
//     c_input_extensions.reserve(input_extensions.size() + 1);
//     std::vector<const char*> c_output_extensions;
//     c_output_extensions.reserve(output_extensions.size() + 1);
//     std::string c_name(name.data(), name.length());
//     std::string c_lib_version(lib_version.data(), lib_version.length());

//     for (auto& ext : input_extensions) {
//         c_input_extensions.push_back(ext.data());
//     }
//     c_input_extensions.push_back(nullptr);

//     for (auto& ext : output_extensions) {
//         c_output_extensions.push_back(ext.data());
//     }
//     c_output_extensions.push_back(nullptr);

//     OIIO::declare_imageio_format(c_name, c_input_creator,
//                                  c_input_extensions.data(),
//                                  (ImageOutput::Creator)(&output_creator),
//                                  c_output_extensions.data(),
//                                  c_lib_version.data());
// }

bool
is_imageio_format_name(const rust::Str name)
{
    return OIIO::is_imageio_format_name(std::string(name));
}

rust::Vec<ExtensionMapItem>
get_extension_map()
{
    auto map = OIIO::get_extension_map();
    rust::Vec<ExtensionMapItem> result;

    for (auto& item : map) {
        ExtensionMapItem i {};
        rust::Vec<rust::String> values {};

        for (auto& value : item.second) {
            values.push_back(rust::String::lossy(value));
        }

        i.key   = rust::String::lossy(item.first);
        i.value = values;
        result.push_back(i);
    }

    return result;
}


bool
convert_pixel_values(TypeDesc src_type, rust::Slice<const uint8_t> src,
                     TypeDesc dst_type, rust::Slice<uint8_t> dst)
{
    return OIIO::convert_pixel_values(src_type, src.data(), dst_type,
                                      dst.data());
}

bool
convert_image(int nchannels, int width, int height, int depth,
              rust::Slice<const uint8_t> src, TypeDesc src_type,
              int64_t src_xstride, int64_t src_ystride, int64_t src_zstride,
              rust::Slice<uint8_t> dst, TypeDesc dst_type, int64_t dst_xstride,
              int64_t dst_ystride, int64_t dst_zstride)
{
    return OIIO::convert_image(nchannels, width, height, depth, src.data(),
                               src_type, src_xstride, src_ystride, src_zstride,
                               dst.data(), dst_type, dst_xstride, dst_ystride,
                               dst_zstride);
}

bool
parallel_convert_image(int nchannels, int width, int height, int depth,
                       rust::Slice<const uint8_t> src, TypeDesc src_type,
                       int64_t src_xstride, int64_t src_ystride,
                       int64_t src_zstride, rust::Slice<uint8_t> dst,
                       TypeDesc dst_type, int64_t dst_xstride,
                       int64_t dst_ystride, int64_t dst_zstride, int nthreads)
{
    return OIIO::parallel_convert_image(nchannels, width, height, depth,
                                        src.data(), src_type, src_xstride,
                                        src_ystride, src_zstride, dst.data(),
                                        dst_type, dst_xstride, dst_ystride,
                                        dst_zstride, nthreads);
}

void
add_dither(int nchannels, int width, int height, int depth, float* data,
           int64_t xstride, int64_t ystride, int64_t zstride,
           float ditheramplitude, int alpha_channel, int z_channel,
           unsigned int ditherseed, int chorigin, int xorigin, int yorigin,
           int zorigin)
{
    OIIO::add_dither(nchannels, width, height, depth, data, xstride, ystride,
                     zstride, ditheramplitude, alpha_channel, z_channel,
                     ditherseed, chorigin, xorigin, yorigin, zorigin);
}

void
premult(int nchannels, int width, int height, int depth, int chbegin, int chend,
        TypeDesc datatype, rust::Slice<uint8_t> data, int64_t xstride,
        int64_t ystride, int64_t zstride, int alpha_channel, int z_channel)
{
    OIIO::premult(nchannels, width, height, depth, chbegin, chend, datatype,
                  data.data(), xstride, ystride, zstride, alpha_channel,
                  z_channel);
}

bool
copy_image(int nchannels, int width, int height, int depth,
           rust::Slice<const uint8_t> src, int64_t pixelsize,
           int64_t src_xstride, int64_t src_ystride, int64_t src_zstride,
           rust::Slice<uint8_t> dst, int64_t dst_xstride, int64_t dst_ystride,
           int64_t dst_zstride)
{
    return OIIO::copy_image(nchannels, width, height, depth, src.data(),
                            pixelsize, src_xstride, src_ystride, src_zstride,
                            dst.data(), dst_xstride, dst_ystride, dst_zstride);
}

bool
wrap_black(int& coord, int origin, int width)
{
    return OIIO::wrap_black(coord, origin, width);
}

bool
wrap_clamp(int& coord, int origin, int width)
{
    return OIIO::wrap_clamp(coord, origin, width);
}

bool
wrap_periodic(int& coord, int origin, int width)
{
    return OIIO::wrap_periodic(coord, origin, width);
}

bool
wrap_periodic_pow2(int& coord, int origin, int width)
{
    return OIIO::wrap_periodic_pow2(coord, origin, width);
}

bool
wrap_mirror(int& coord, int origin, int width)
{
    return OIIO::wrap_mirror(coord, origin, width);
}

void
debug(const rust::Str message)
{
    // See imageinput_seterror: OIIO::debug takes a string_view but the
    // const char* conversion would scan for a NUL that is not there.
    OIIO::debug(to_string_view(message));
}
#pragma endregion
}  // namespace oiio