aboutsummaryrefslogtreecommitdiff
path: root/tools/cddl/codegen.cc
blob: a763b7211d6d0266b6ff527de62a469d1b5e50f5 (plain)
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "tools/cddl/codegen.h"

#include <cinttypes>
#include <iostream>
#include <limits>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

#include "absl/algorithm/container.h"
#include "absl/types/optional.h"

// Convert '-' to '_' to use a CDDL identifier as a C identifier.
std::string ToUnderscoreId(const std::string& x) {
  std::string result(x);
  for (auto& c : result) {
    if (c == '-')
      c = '_';
  }
  return result;
}

// Convert a CDDL identifier to camel case for use as a C typename.  E.g.
// presentation-connection-message to PresentationConnectionMessage.
std::string ToCamelCase(const std::string& x) {
  std::string result(x);
  result[0] = toupper(result[0]);
  size_t new_size = 1;
  size_t result_size = result.size();
  for (size_t i = 1; i < result_size; ++i, ++new_size) {
    if (result[i] == '-') {
      ++i;
      if (i < result_size)
        result[new_size] = toupper(result[i]);
    } else {
      result[new_size] = result[i];
    }
  }
  result.resize(new_size);
  return result;
}

// Returns a string which represents the C++ type of |cpp_type|.  Returns an
// empty string if there is no valid representation for |cpp_type| (e.g. a
// vector with an invalid element type).
std::string CppTypeToString(const CppType& cpp_type) {
  switch (cpp_type.which) {
    case CppType::Which::kUint64:
      return "uint64_t";
    case CppType::Which::kString:
      return "std::string";
    case CppType::Which::kBytes: {
      if (cpp_type.bytes_type.fixed_size) {
        std::string size_string =
            std::to_string(cpp_type.bytes_type.fixed_size.value());
        return "std::array<uint8_t, " + size_string + ">";
      } else {
        return "std::vector<uint8_t>";
      }
    }
    case CppType::Which::kVector: {
      std::string element_string =
          CppTypeToString(*cpp_type.vector_type.element_type);
      if (element_string.empty())
        return std::string();
      return "std::vector<" + element_string + ">";
    }
    case CppType::Which::kEnum:
      return ToCamelCase(cpp_type.name);
    case CppType::Which::kStruct:
      return ToCamelCase(cpp_type.name);
    case CppType::Which::kTaggedType:
      return CppTypeToString(*cpp_type.tagged_type.real_type);
    default:
      return std::string();
  }
}

bool WriteEnumEqualityOperatorSwitchCases(int fd,
                                          const CppType& parent,
                                          std::string child_name,
                                          std::string parent_name) {
  for (const auto& x : parent.enum_type.members) {
    std::string enum_value = "k" + ToCamelCase(x.first);
    dprintf(fd, "    case %s::%s: return parent == %s::%s;\n",
            child_name.c_str(), enum_value.c_str(), parent_name.c_str(),
            enum_value.c_str());
  }

  return absl::c_all_of(parent.enum_type.sub_members,
                        [&fd, &child_name, &parent_name](CppType* new_parent) {
                          return WriteEnumEqualityOperatorSwitchCases(
                              fd, *new_parent, child_name, parent_name);
                        });
}

// Write the equality operators for comparing an enum and its parent types.
bool WriteEnumEqualityOperator(int fd,
                               const CppType& type,
                               const CppType& parent) {
  std::string name = ToCamelCase(type.name);
  std::string parent_name = ToCamelCase(parent.name);

  // Define type == parentType.
  dprintf(fd, "inline bool operator==(const %s& child, const %s& parent) {\n",
          name.c_str(), parent_name.c_str());
  dprintf(fd, "  switch (child) {\n");
  if (!WriteEnumEqualityOperatorSwitchCases(fd, parent, name, parent_name)) {
    return false;
  }
  dprintf(fd, "    default: return false;\n");
  dprintf(fd, "  }\n}\n");

  // Define parentType == type.
  dprintf(fd, "inline bool operator==(const %s& parent, const %s& child) {\n",
          parent_name.c_str(), name.c_str());
  dprintf(fd, "  return child == parent;\n}\n");

  // Define type != parentType.
  dprintf(fd, "inline bool operator!=(const %s& child, const %s& parent) {\n",
          name.c_str(), parent_name.c_str());
  dprintf(fd, "  return !(child == parent);\n}\n");

  // Define parentType != type.
  dprintf(fd, "inline bool operator!=(const %s& parent, const %s& child) {\n",
          parent_name.c_str(), name.c_str());
  dprintf(fd, "  return !(parent == child);\n}\n");

  return true;
}

bool WriteEnumStreamOperatorSwitchCases(int fd,
                                        const CppType& type,
                                        std::string name) {
  for (const auto& x : type.enum_type.members) {
    std::string enum_value = "k" + ToCamelCase(x.first);
    dprintf(fd, "    case %s::%s: os << \"%s\"; break;\n", name.c_str(),
            enum_value.c_str(), enum_value.c_str());
  }

  return absl::c_all_of(
      type.enum_type.sub_members, [&fd, &name](CppType* parent) {
        return WriteEnumStreamOperatorSwitchCases(fd, *parent, name);
      });
}

bool WriteEnumOperators(int fd, const CppType& type) {
  // Write << operator.
  std::string name = ToCamelCase(type.name);
  dprintf(
      fd,
      "inline std::ostream& operator<<(std::ostream& os, const %s& val) {\n",
      name.c_str());
  dprintf(fd, "  switch (val) {\n");
  if (!WriteEnumStreamOperatorSwitchCases(fd, type, name)) {
    return false;
  }
  dprintf(fd,
          "    default: os << \"Unknown Value: \" << static_cast<int>(val);"
          "\n      break;\n    }\n  return os;\n}\n");

  // Write equality operators.
  return absl::c_all_of(type.enum_type.sub_members,
                        [&fd, &type](CppType* parent) {
                          return WriteEnumEqualityOperator(fd, type, *parent);
                        });
}

// Writes the equality operator for a specific Discriminated Union.
bool WriteDiscriminatedUnionEqualityOperator(
    int fd,
    const CppType& type,
    const std::string& name_prefix = "") {
  const std::string name = name_prefix + ToCamelCase(type.name);
  dprintf(fd, "\nbool %s::operator==(const %s& other) const {\n", name.c_str(),
          name.c_str());
  dprintf(fd, "  return this->which == other.which");
  for (auto* union_member : type.discriminated_union.members) {
    dprintf(fd, " &&\n         ");
    switch (union_member->which) {
      case CppType::Which::kUint64:
        dprintf(fd,
                "(this->which != Which::kUint64 || this->uint == other.uint)");
        break;
      case CppType::Which::kString:
        dprintf(fd,
                "(this->which != Which::kString || this->str == other.str)");
        break;
      case CppType::Which::kBytes:
        dprintf(fd,
                "(this->which != Which::kBytes || this->bytes == other.bytes)");
        break;
      default:
        return false;
    }
  }
  dprintf(fd, ";\n}\n");
  dprintf(fd, "bool %s::operator!=(const %s& other) const {\n", name.c_str(),
          name.c_str());
  dprintf(fd, "  return !(*this == other);\n}\n");
  return true;
}

// Writes the equality operator for a specific C++ struct.
bool WriteStructEqualityOperator(int fd,
                                 const CppType& type,
                                 const std::string& name_prefix = "") {
  const std::string name = name_prefix + ToCamelCase(type.name);
  dprintf(fd, "\nbool %s::operator==(const %s& other) const {\n", name.c_str(),
          name.c_str());
  for (size_t i = 0; i < type.struct_type.members.size(); i++) {
    if (i == 0) {
      dprintf(fd, "  return ");
    } else {
      dprintf(fd, " &&\n         ");
    }
    auto name = ToUnderscoreId(type.struct_type.members[i].name);
    dprintf(fd, "this->%s == other.%s", name.c_str(), name.c_str());
  }
  dprintf(fd, ";\n}");
  dprintf(fd, "\nbool %s::operator!=(const %s& other) const {\n", name.c_str(),
          name.c_str());
  dprintf(fd, "  return !(*this == other);\n}\n");
  std::string new_prefix = name_prefix + ToCamelCase(type.name) + "::";
  for (const auto& x : type.struct_type.members) {
    // NOTE: Don't need to call recursively on struct members, since all structs
    // are handled in the calling method.
    if (x.type->which == CppType::Which::kDiscriminatedUnion) {
      if (!WriteDiscriminatedUnionEqualityOperator(fd, *x.type, new_prefix)) {
        return false;
      }
    }
  }
  return true;
}

// Write the C++ struct member definitions of every type in |members| to the
// file descriptor |fd|.
bool WriteStructMembers(
    int fd,
    const std::string& name,
    const std::vector<CppType::Struct::CppMember>& members) {
  for (const auto& x : members) {
    std::string type_string;
    switch (x.type->which) {
      case CppType::Which::kStruct: {
        if (x.type->struct_type.key_type ==
            CppType::Struct::KeyType::kPlainGroup) {
          if (!WriteStructMembers(fd, x.type->name,
                                  x.type->struct_type.members))
            return false;
          continue;
        } else {
          type_string = ToCamelCase(x.name);
        }
      } break;
      case CppType::Which::kOptional: {
        // TODO(btolsch): Make this optional<T> when one lands.
        dprintf(fd, "  bool has_%s;\n", ToUnderscoreId(x.name).c_str());
        type_string = CppTypeToString(*x.type->optional_type);
      } break;
      case CppType::Which::kDiscriminatedUnion: {
        std::string cid = ToUnderscoreId(x.name);
        type_string = ToCamelCase(x.name);
        dprintf(fd, "  struct %s {\n", type_string.c_str());
        dprintf(fd, "    %s();\n    ~%s();\n\n", type_string.c_str(),
                type_string.c_str());

        dprintf(fd, "  bool operator==(const %s& other) const;\n",
                type_string.c_str());
        dprintf(fd, "  bool operator!=(const %s& other) const;\n\n",
                type_string.c_str());
        dprintf(fd, "  enum class Which {\n");
        for (auto* union_member : x.type->discriminated_union.members) {
          switch (union_member->which) {
            case CppType::Which::kUint64:
              dprintf(fd, "    kUint64,\n");
              break;
            case CppType::Which::kString:
              dprintf(fd, "    kString,\n");
              break;
            case CppType::Which::kBytes:
              dprintf(fd, "    kBytes,\n");
              break;
            default:
              return false;
          }
        }
        dprintf(fd, "    kUninitialized,\n");
        dprintf(fd, "  } which;\n");
        dprintf(fd, "  union {\n");
        for (auto* union_member : x.type->discriminated_union.members) {
          switch (union_member->which) {
            case CppType::Which::kUint64:
              dprintf(fd, "    uint64_t uint;\n");
              break;
            case CppType::Which::kString:
              dprintf(fd, "    std::string str;\n");
              break;
            case CppType::Which::kBytes:
              dprintf(fd, "    std::vector<uint8_t> bytes;\n");
              break;
            default:
              return false;
          }
        }
        // NOTE: This member allows the union to be easily constructed in an
        // effectively uninitialized state.  Its value should never be used.
        dprintf(fd, "    bool placeholder_;\n");
        dprintf(fd, "  };\n");
        dprintf(fd, "  };\n");
      } break;
      default:
        type_string = CppTypeToString(*x.type);
        break;
    }
    if (type_string.empty())
      return false;
    dprintf(fd, "  %s %s;\n", type_string.c_str(),
            ToUnderscoreId(x.name).c_str());
  }
  return true;
}

void WriteEnumMembers(int fd, const CppType& type) {
  for (const auto& x : type.enum_type.members) {
    dprintf(fd, "  k%s = %" PRIu64 "ull,\n", ToCamelCase(x.first).c_str(),
            x.second);
  }
  for (const auto* x : type.enum_type.sub_members) {
    WriteEnumMembers(fd, *x);
  }
}

// Writes a C++ type definition for |type| to the file descriptor |fd|.  This
// only generates a definition for enums and structs.
bool WriteTypeDefinition(int fd, const CppType& type) {
  std::string name = ToCamelCase(type.name);
  switch (type.which) {
    case CppType::Which::kEnum: {
      dprintf(fd, "\nenum class %s : uint64_t {\n", name.c_str());
      WriteEnumMembers(fd, type);
      dprintf(fd, "};\n");
      if (!WriteEnumOperators(fd, type))
        return false;
    } break;
    case CppType::Which::kStruct: {
      dprintf(fd, "\nstruct %s {\n", name.c_str());
      if (type.type_key != absl::nullopt) {
        dprintf(fd, "  // type key: %" PRIu64 "\n", type.type_key.value());
      }
      dprintf(fd, "  bool operator==(const %s& other) const;\n", name.c_str());
      dprintf(fd, "  bool operator!=(const %s& other) const;\n\n",
              name.c_str());
      if (!WriteStructMembers(fd, type.name, type.struct_type.members))
        return false;
      dprintf(fd, "};\n");
    } break;
    default:
      break;
  }
  return true;
}

// Ensures that any dependencies within |cpp_type| are written to the file
// descriptor |fd| before writing |cpp_type| to the file descriptor |fd|.  This
// is done by walking the tree of types defined by |cpp_type| (e.g. all the
// members for a struct).  |defs| contains the names of types that have already
// been written.  If a type hasn't been written and needs to be, its name will
// also be added to |defs|.
bool EnsureDependentTypeDefinitionsWritten(int fd,
                                           const CppType& cpp_type,
                                           std::set<std::string>* defs) {
  switch (cpp_type.which) {
    case CppType::Which::kVector: {
      return EnsureDependentTypeDefinitionsWritten(
          fd, *cpp_type.vector_type.element_type, defs);
    }
    case CppType::Which::kEnum: {
      if (defs->find(cpp_type.name) != defs->end())
        return true;
      for (const auto* x : cpp_type.enum_type.sub_members)
        if (!EnsureDependentTypeDefinitionsWritten(fd, *x, defs))
          return false;
      defs->emplace(cpp_type.name);
      WriteTypeDefinition(fd, cpp_type);
    } break;
    case CppType::Which::kStruct: {
      if (cpp_type.struct_type.key_type !=
          CppType::Struct::KeyType::kPlainGroup) {
        if (defs->find(cpp_type.name) != defs->end())
          return true;
        for (const auto& x : cpp_type.struct_type.members)
          if (!EnsureDependentTypeDefinitionsWritten(fd, *x.type, defs))
            return false;
        defs->emplace(cpp_type.name);
        WriteTypeDefinition(fd, cpp_type);
      }
    } break;
    case CppType::Which::kOptional: {
      return EnsureDependentTypeDefinitionsWritten(fd, *cpp_type.optional_type,
                                                   defs);
    }
    case CppType::Which::kDiscriminatedUnion: {
      for (const auto* x : cpp_type.discriminated_union.members)
        if (!EnsureDependentTypeDefinitionsWritten(fd, *x, defs))
          return false;
    } break;
    case CppType::Which::kTaggedType: {
      if (!EnsureDependentTypeDefinitionsWritten(
              fd, *cpp_type.tagged_type.real_type, defs)) {
        return false;
      }
    } break;
    default:
      break;
  }
  return true;
}

// Writes the type definition for every C++ type in |table|.  This function
// makes sure to write them in such an order that all type dependencies are
// written before they are need so the resulting text in the file descriptor
// |fd| will compile without modification.  For example, the following would be
// bad output:
//
// struct Foo {
//   Bar bar;
//   int x;
// };
//
// struct Bar {
//   int alpha;
// };
//
// This function ensures that Bar would be written sometime before Foo.
bool WriteTypeDefinitions(int fd, CppSymbolTable* table) {
  std::set<std::string> defs;
  for (const std::unique_ptr<CppType>& real_type : table->cpp_types) {
    if (real_type->which != CppType::Which::kStruct ||
        real_type->struct_type.key_type ==
            CppType::Struct::KeyType::kPlainGroup) {
      continue;
    }
    if (!EnsureDependentTypeDefinitionsWritten(fd, *real_type, &defs))
      return false;
  }

  dprintf(fd, "\nenum class Type : uint64_t {\n");
  dprintf(fd, "    kUnknown = 0ull,\n");
  for (CppType* type : table->TypesWithId()) {
    dprintf(fd, "    k%s = %" PRIu64 "ull,\n", ToCamelCase(type->name).c_str(),
            type->type_key.value());
  }
  dprintf(fd, "};\n");
  return true;
}

// Writes a parser that takes in a uint64_t and outputs the corresponding Type
// if one matches up, or Type::kUnknown if none does.
// NOTE: In future, this could be changes to use a Trie, which would allow for
// manufacturers to more easily add their own type ids to ours.
bool WriteTypeParserDefinition(int fd, CppSymbolTable* table) {
  dprintf(fd, "\n//static\n");
  dprintf(fd, "Type TypeEnumValidator::SafeCast(uint64_t type_id) {\n");
  dprintf(fd, "  switch (type_id) {\n");
  for (CppType* type : table->TypesWithId()) {
    dprintf(fd, "    case uint64_t{%" PRIu64 "}: return Type::k%s;\n",
            type->type_key.value(), ToCamelCase(type->name).c_str());
  }
  dprintf(fd, "    default: return Type::kUnknown;\n");
  dprintf(fd, "  }\n}\n");
  return true;
}

// Writes the function prototypes for the encode and decode functions for each
// type in |table| to the file descriptor |fd|.
bool WriteFunctionDeclarations(int fd, CppSymbolTable* table) {
  for (CppType* real_type : table->TypesWithId()) {
    const auto& name = real_type->name;
    if (real_type->which != CppType::Which::kStruct ||
        real_type->struct_type.key_type ==
            CppType::Struct::KeyType::kPlainGroup) {
      return false;
    }
    std::string cpp_name = ToCamelCase(name);
    dprintf(fd, "\nbool Encode%s(\n", cpp_name.c_str());
    dprintf(fd, "    const %s& data,\n", cpp_name.c_str());
    dprintf(fd, "    CborEncodeBuffer* buffer);\n");
    dprintf(fd, "ssize_t Encode%s(\n", cpp_name.c_str());
    dprintf(fd, "    const %s& data,\n", cpp_name.c_str());
    dprintf(fd, "    uint8_t* buffer,\n    size_t length);\n");
    dprintf(fd, "ssize_t Decode%s(\n", cpp_name.c_str());
    dprintf(fd, "    const uint8_t* buffer,\n    size_t length,\n");
    dprintf(fd, "    %s* data);\n", cpp_name.c_str());
  }
  return true;
}

bool WriteMapEncoder(int fd,
                     const std::string& name,
                     const std::vector<CppType::Struct::CppMember>& members,
                     const std::string& nested_type_scope,
                     int encoder_depth = 1);
bool WriteArrayEncoder(int fd,
                       const std::string& name,
                       const std::vector<CppType::Struct::CppMember>& members,
                       const std::string& nested_type_scope,
                       int encoder_depth = 1);

// Writes the encoding function for the C++ type |cpp_type| to the file
// descriptor |fd|.  |name| is the C++ variable name that needs to be encoded.
// |nested_type_scope| is the closest C++ scope name (i.e. struct name), which
// may be used to access local enum constants.  |encoder_depth| is used to
// independently name independent cbor encoders that need to be created.
bool WriteEncoder(int fd,
                  const std::string& name,
                  const CppType& cpp_type,
                  const std::string& nested_type_scope,
                  int encoder_depth) {
  switch (cpp_type.which) {
    case CppType::Which::kStruct:
      if (cpp_type.struct_type.key_type == CppType::Struct::KeyType::kMap) {
        if (!WriteMapEncoder(fd, name, cpp_type.struct_type.members,
                             cpp_type.name, encoder_depth + 1)) {
          return false;
        }
        return true;
      } else if (cpp_type.struct_type.key_type ==
                 CppType::Struct::KeyType::kArray) {
        if (!WriteArrayEncoder(fd, name, cpp_type.struct_type.members,
                               cpp_type.name, encoder_depth + 1)) {
          return false;
        }
        return true;
      } else {
        for (const auto& x : cpp_type.struct_type.members) {
          if (x.integer_key.has_value()) {
            dprintf(fd,
                    "  CBOR_RETURN_ON_ERROR(cbor_encode_uint("
                    "&encoder%d, %" PRIu64 ");\n",
                    encoder_depth, x.integer_key.value());
          } else {
            dprintf(fd,
                    "  CBOR_RETURN_ON_ERROR(cbor_encode_text_string("
                    "&encoder%d, \"%s\", sizeof(\"%s\") - 1));\n",
                    encoder_depth, x.name.c_str(), x.name.c_str());
          }
          if (!WriteEncoder(fd, name + "." + ToUnderscoreId(x.name), *x.type,
                            nested_type_scope, encoder_depth)) {
            return false;
          }
        }
        return true;
      }
    case CppType::Which::kUint64:
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_encode_uint(&encoder%d, %s));\n",
              encoder_depth, ToUnderscoreId(name).c_str());
      return true;
    case CppType::Which::kString: {
      std::string cid = ToUnderscoreId(name);
      dprintf(fd, "  if (!IsValidUtf8(%s)) {\n", cid.c_str());
      dprintf(fd, "    return -CborErrorInvalidUtf8TextString;\n");
      dprintf(fd, "  }\n");
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encode_text_string(&encoder%d, "
              "%s.c_str(), %s.size()));\n",
              encoder_depth, cid.c_str(), cid.c_str());
      return true;
    }
    case CppType::Which::kBytes: {
      std::string cid = ToUnderscoreId(name);
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encode_byte_string(&encoder%d, "
              "%s.data(), "
              "%s.size()));\n",
              encoder_depth, cid.c_str(), cid.c_str());
      return true;
    }
    case CppType::Which::kVector: {
      std::string cid = ToUnderscoreId(name);
      dprintf(fd, "  {\n");
      if (cpp_type.vector_type.min_length !=
          CppType::Vector::kMinLengthUnbounded) {
        dprintf(fd, "  if (%s.size() < %d) {\n", cid.c_str(),
                cpp_type.vector_type.min_length);
        dprintf(fd, "    return -CborErrorTooFewItems;\n");
        dprintf(fd, "  }\n");
      }
      if (cpp_type.vector_type.max_length !=
          CppType::Vector::kMaxLengthUnbounded) {
        dprintf(fd, "  if (%s.size() > %d) {\n", cid.c_str(),
                cpp_type.vector_type.max_length);
        dprintf(fd, "    return -CborErrorTooManyItems;\n");
        dprintf(fd, "  }\n");
      }
      dprintf(fd, "  CborEncoder encoder%d;\n", encoder_depth + 1);
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encoder_create_array(&encoder%d, "
              "&encoder%d, %s.size()));\n",
              encoder_depth, encoder_depth + 1, cid.c_str());
      dprintf(fd, "  for (const auto& x : %s) {\n", cid.c_str());
      if (!WriteEncoder(fd, "x", *cpp_type.vector_type.element_type,
                        nested_type_scope, encoder_depth + 1)) {
        return false;
      }
      dprintf(fd, "  }\n");
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encoder_close_container(&encoder%d, "
              "&encoder%d));\n",
              encoder_depth, encoder_depth + 1);
      dprintf(fd, "  }\n");
      return true;
    }
    case CppType::Which::kEnum: {
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encode_uint(&encoder%d, "
              "static_cast<uint64_t>(%s)));\n",
              encoder_depth, ToUnderscoreId(name).c_str());
      return true;
    }
    case CppType::Which::kDiscriminatedUnion: {
      for (const auto* union_member : cpp_type.discriminated_union.members) {
        switch (union_member->which) {
          case CppType::Which::kUint64:
            dprintf(fd, "  case %s::%s::Which::kUint64:\n",
                    ToCamelCase(nested_type_scope).c_str(),
                    ToCamelCase(cpp_type.name).c_str());
            if (!WriteEncoder(fd, ToUnderscoreId(name + ".uint"), *union_member,
                              nested_type_scope, encoder_depth)) {
              return false;
            }
            dprintf(fd, "    break;\n");
            break;
          case CppType::Which::kString:
            dprintf(fd, "  case %s::%s::Which::kString:\n",
                    ToCamelCase(nested_type_scope).c_str(),
                    ToCamelCase(cpp_type.name).c_str());
            if (!WriteEncoder(fd, ToUnderscoreId(name + ".str"), *union_member,
                              nested_type_scope, encoder_depth)) {
              return false;
            }
            dprintf(fd, "    break;\n");
            break;
          case CppType::Which::kBytes:
            dprintf(fd, "  case %s::%s::Which::kBytes:\n",
                    ToCamelCase(nested_type_scope).c_str(),
                    ToCamelCase(cpp_type.name).c_str());
            if (!WriteEncoder(fd, ToUnderscoreId(name + ".bytes"),
                              *union_member, nested_type_scope,
                              encoder_depth)) {
              return false;
            }
            dprintf(fd, "    break;\n");
            break;
          default:
            return false;
        }
      }
      dprintf(fd, "  case %s::%s::Which::kUninitialized:\n",
              ToCamelCase(nested_type_scope).c_str(),
              ToCamelCase(cpp_type.name).c_str());
      dprintf(fd, "    return -CborUnknownError;\n");
      return true;
    }
    case CppType::Which::kTaggedType: {
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_encode_tag(&encoder%d, %" PRIu64
              "ull));\n",
              encoder_depth, cpp_type.tagged_type.tag);
      if (!WriteEncoder(fd, name, *cpp_type.tagged_type.real_type,
                        nested_type_scope, encoder_depth)) {
        return false;
      }
      return true;
    }
    default:
      break;
  }
  return false;
}

struct MemberCountResult {
  int num_required;
  int num_optional;
};

MemberCountResult CountMemberTypes(
    int fd,
    const std::string& name_id,
    const std::vector<CppType::Struct::CppMember>& members) {
  int num_required = 0;
  int num_optional = 0;
  for (const auto& x : members) {
    if (x.type->which == CppType::Which::kOptional) {
      std::string x_id = ToUnderscoreId(x.name);
      if (num_optional == 0) {
        dprintf(fd, "  int num_optionals_present = %s.has_%s;\n",
                name_id.c_str(), x_id.c_str());
      } else {
        dprintf(fd, "  num_optionals_present += %s.has_%s;\n", name_id.c_str(),
                x_id.c_str());
      }
      ++num_optional;
    } else {
      ++num_required;
    }
  }
  return MemberCountResult{num_required, num_optional};
}

// Writes the encoding function for a CBOR map with the C++ type members in
// |members| to the file descriptor |fd|.  |name| is the C++ variable name that
// needs to be encoded.  |nested_type_scope| is the closest C++ scope name (i.e.
// struct name), which may be used to access local enum constants.
// |encoder_depth| is used to independently name independent cbor encoders that
// need to be created.
bool WriteMapEncoder(int fd,
                     const std::string& name,
                     const std::vector<CppType::Struct::CppMember>& members,
                     const std::string& nested_type_scope,
                     int encoder_depth) {
  std::string name_id = ToUnderscoreId(name);
  dprintf(fd, "  CborEncoder encoder%d;\n", encoder_depth);
  MemberCountResult member_counts = CountMemberTypes(fd, name_id, members);
  if (member_counts.num_optional == 0) {
    dprintf(fd,
            "  CBOR_RETURN_ON_ERROR(cbor_encoder_create_map(&encoder%d, "
            "&encoder%d, "
            "%d));\n",
            encoder_depth - 1, encoder_depth, member_counts.num_required);
  } else {
    dprintf(fd,
            "  CBOR_RETURN_ON_ERROR(cbor_encoder_create_map(&encoder%d, "
            "&encoder%d, "
            "%d + num_optionals_present));\n",
            encoder_depth - 1, encoder_depth, member_counts.num_required);
  }

  for (const auto& x : members) {
    std::string fullname = name;
    CppType* member_type = x.type;
    if (x.type->which != CppType::Which::kStruct ||
        x.type->struct_type.key_type != CppType::Struct::KeyType::kPlainGroup) {
      if (x.type->which == CppType::Which::kOptional) {
        member_type = x.type->optional_type;
        dprintf(fd, "  if (%s.has_%s) {\n", name_id.c_str(),
                ToUnderscoreId(x.name).c_str());
      }

      if (x.integer_key.has_value()) {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(cbor_encode_uint(&encoder%d, %" PRIu64
                "));\n",
                encoder_depth, x.integer_key.value());
      } else {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(cbor_encode_text_string(&encoder%d, "
                "\"%s\", sizeof(\"%s\") - 1));\n",
                encoder_depth, x.name.c_str(), x.name.c_str());
      }
      if (x.type->which == CppType::Which::kDiscriminatedUnion) {
        dprintf(fd, "  switch (%s.%s.which) {\n", fullname.c_str(),
                x.name.c_str());
      }
      fullname = fullname + "." + x.name;
    }
    if (!WriteEncoder(fd, fullname, *member_type, nested_type_scope,
                      encoder_depth)) {
      return false;
    }
    if (x.type->which == CppType::Which::kOptional ||
        x.type->which == CppType::Which::kDiscriminatedUnion) {
      dprintf(fd, "  }\n");
    }
  }

  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_encoder_close_container(&encoder%d, "
          "&encoder%d));\n",
          encoder_depth - 1, encoder_depth);
  return true;
}

// Writes the encoding function for a CBOR array with the C++ type members in
// |members| to the file descriptor |fd|.  |name| is the C++ variable name that
// needs to be encoded.  |nested_type_scope| is the closest C++ scope name (i.e.
// struct name), which may be used to access local enum constants.
// |encoder_depth| is used to independently name independent cbor encoders that
// need to be created.
bool WriteArrayEncoder(int fd,
                       const std::string& name,
                       const std::vector<CppType::Struct::CppMember>& members,
                       const std::string& nested_type_scope,
                       int encoder_depth) {
  std::string name_id = ToUnderscoreId(name);
  dprintf(fd, "  CborEncoder encoder%d;\n", encoder_depth);
  MemberCountResult member_counts = CountMemberTypes(fd, name_id, members);
  if (member_counts.num_optional == 0) {
    dprintf(fd,
            "  CBOR_RETURN_ON_ERROR(cbor_encoder_create_array(&encoder%d, "
            "&encoder%d, %d));\n",
            encoder_depth - 1, encoder_depth, member_counts.num_required);
  } else {
    dprintf(fd,
            "  CBOR_RETURN_ON_ERROR(cbor_encoder_create_array(&encoder%d, "
            "&encoder%d, %d + num_optionals_present));\n",
            encoder_depth - 1, encoder_depth, member_counts.num_required);
  }

  for (const auto& x : members) {
    std::string fullname = name;
    CppType* member_type = x.type;
    if (x.type->which != CppType::Which::kStruct ||
        x.type->struct_type.key_type != CppType::Struct::KeyType::kPlainGroup) {
      if (x.type->which == CppType::Which::kOptional) {
        member_type = x.type->optional_type;
        dprintf(fd, "  if (%s.has_%s) {\n", name_id.c_str(),
                ToUnderscoreId(x.name).c_str());
      }
      if (x.type->which == CppType::Which::kDiscriminatedUnion) {
        dprintf(fd, "  switch (%s.%s.which) {\n", fullname.c_str(),
                x.name.c_str());
      }
      fullname = fullname + "." + x.name;
    }
    if (!WriteEncoder(fd, fullname, *member_type, nested_type_scope,
                      encoder_depth)) {
      return false;
    }
    if (x.type->which == CppType::Which::kOptional ||
        x.type->which == CppType::Which::kDiscriminatedUnion) {
      dprintf(fd, "  }\n");
    }
  }

  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_encoder_close_container(&encoder%d, "
          "&encoder%d));\n",
          encoder_depth - 1, encoder_depth);
  return true;
}

uint8_t GetByte(uint64_t value, size_t byte) {
  return static_cast<uint8_t>((value >> (byte * 8)) & 0xFF);
}

std::string GetEncodedTypeKey(const CppType& type) {
  if (type.type_key == absl::nullopt) {
    return "";
  }

  // Determine all constants needed for calculating the encoded id bytes.
  uint64_t type_id = type.type_key.value();
  uint8_t encoding_size;
  uint8_t start_processing_byte;
  if (type_id < 0x1 << 6) {
    encoding_size = 0x0;
    start_processing_byte = 0;
  } else if (type_id < 0x1 << 14) {
    encoding_size = 0x01;
    start_processing_byte = 1;
  } else if (type_id < 0x1 << 30) {
    encoding_size = 0x02;
    start_processing_byte = 3;
  } else if (type_id < uint64_t{0x1} << 62) {
    encoding_size = 0x03;
    start_processing_byte = 7;
  } else {
    return "";
  }

  // Parse the encoded id into a string;
  std::stringstream ss;
  uint8_t first_byte =
      encoding_size << 6 | GetByte(type_id, start_processing_byte);
  ss << "{0x" << std::hex << uint32_t{first_byte};
  for (int i = start_processing_byte - 1; i >= 0; i--) {
    ss << ", 0x" << std::hex << uint32_t{GetByte(type_id, i)};
  }
  ss << "}";
  return ss.str();
}

// Writes encoding functions for each type in |table| to the file descriptor
// |fd|.
bool WriteEncoders(int fd, CppSymbolTable* table) {
  for (CppType* real_type : table->TypesWithId()) {
    const auto& name = real_type->name;
    if (real_type->which != CppType::Which::kStruct ||
        real_type->struct_type.key_type ==
            CppType::Struct::KeyType::kPlainGroup) {
      return false;
    }
    std::string cpp_name = ToCamelCase(name);

    for (const auto& x : real_type->struct_type.members) {
      if (x.type->which != CppType::Which::kDiscriminatedUnion)
        continue;
      std::string dunion_cpp_name = ToCamelCase(x.name);
      dprintf(fd, "\n%s::%s::%s()\n", cpp_name.c_str(), dunion_cpp_name.c_str(),
              dunion_cpp_name.c_str());
      std::string cid = ToUnderscoreId(x.name);
      std::string type_name = ToCamelCase(x.name);
      dprintf(fd,
              "    : which(Which::kUninitialized), placeholder_(false) {}\n");

      dprintf(fd, "\n%s::%s::~%s() {\n", cpp_name.c_str(),
              dunion_cpp_name.c_str(), dunion_cpp_name.c_str());
      dprintf(fd, "  switch (which) {\n");
      for (const auto* y : x.type->discriminated_union.members) {
        switch (y->which) {
          case CppType::Which::kUint64: {
            dprintf(fd, " case Which::kUint64: break;\n");
          } break;
          case CppType::Which::kString: {
            dprintf(fd, "  case Which::kString:\n");
            dprintf(fd, "    str.std::string::~basic_string();\n");
            dprintf(fd, "    break;\n");
          } break;
          case CppType::Which::kBytes: {
            dprintf(fd, "  case Which::kBytes:\n");
            dprintf(fd, "    bytes.std::vector<uint8_t>::~vector();\n");
            dprintf(fd, "    break;\n");
          } break;
          default:
            return false;
        }
      }
      dprintf(fd, " case Which::kUninitialized: break;\n");
      dprintf(fd, "  }\n");
      dprintf(fd, "}\n");
    }

    static const char vector_encode_function[] =
        R"(
bool Encode%1$s(
    const %1$s& data,
    CborEncodeBuffer* buffer) {
  if (buffer->AvailableLength() == 0 &&
      !buffer->Append(CborEncodeBuffer::kDefaultInitialEncodeBufferSize))
    return false;
  const uint8_t type_id[] = %2$s;
  if(!buffer->SetType(type_id, sizeof(type_id))) {
    return false;
  }
  while (true) {
    size_t available_length = buffer->AvailableLength();
    ssize_t error_or_size = msgs::Encode%1$s(
        data, buffer->Position(), available_length);
    if (IsError(error_or_size)) {
      return false;
    } else if (error_or_size > static_cast<ssize_t>(available_length)) {
      if (!buffer->ResizeBy(error_or_size - available_length))
        return false;
    } else {
      buffer->ResizeBy(error_or_size - available_length);
      return true;
    }
  }
}
)";

    std::string encoded_id = GetEncodedTypeKey(*real_type);
    if (encoded_id.empty()) {
      return false;
    }

    dprintf(fd, vector_encode_function, cpp_name.c_str(), encoded_id.c_str());
    dprintf(fd, "\nssize_t Encode%s(\n", cpp_name.c_str());
    dprintf(fd, "    const %s& data,\n", cpp_name.c_str());
    dprintf(fd, "    uint8_t* buffer,\n    size_t length) {\n");
    dprintf(fd, "  CborEncoder encoder0;\n");
    dprintf(fd, "  cbor_encoder_init(&encoder0, buffer, length, 0);\n");

    if (real_type->struct_type.key_type == CppType::Struct::KeyType::kMap) {
      if (!WriteMapEncoder(fd, "data", real_type->struct_type.members, name))
        return false;
    } else {
      if (!WriteArrayEncoder(fd, "data", real_type->struct_type.members,
                             name)) {
        return false;
      }
    }

    dprintf(fd,
            "  size_t extra_bytes_needed = "
            "cbor_encoder_get_extra_bytes_needed(&encoder0);\n");
    dprintf(fd, "  if (extra_bytes_needed) {\n");
    dprintf(fd,
            "    return static_cast<ssize_t>(length + extra_bytes_needed);\n");
    dprintf(fd, "  } else {\n");
    dprintf(fd,
            "    return "
            "static_cast<ssize_t>(cbor_encoder_get_buffer_size(&encoder0, "
            "buffer));\n");
    dprintf(fd, "  }\n");
    dprintf(fd, "}\n");
  }
  return true;
}

bool WriteMapDecoder(int fd,
                     const std::string& name,
                     const std::string& member_accessor,
                     const std::vector<CppType::Struct::CppMember>& members,
                     int decoder_depth,
                     int* temporary_count);
bool WriteArrayDecoder(int fd,
                       const std::string& name,
                       const std::string& member_accessor,
                       const std::vector<CppType::Struct::CppMember>& members,
                       int decoder_depth,
                       int* temporary_count);

// Writes the decoding function for the C++ type |cpp_type| to the file
// descriptor |fd|.  |name| is the C++ variable name that needs to be encoded.
// |member_accessor| is either "." or "->" depending on whether |name| is a
// pointer type.  |decoder_depth| is used to independently name independent cbor
// decoders that need to be created.  |temporary_count| is used to ensure
// temporaries get unique names by appending an automatically incremented
// integer.
bool WriteDecoder(int fd,
                  const std::string& name,
                  const std::string& member_accessor,
                  const CppType& cpp_type,
                  int decoder_depth,
                  int* temporary_count) {
  switch (cpp_type.which) {
    case CppType::Which::kUint64: {
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_get_uint64(&it%d, &%s));\n",
              decoder_depth, name.c_str());
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_value_advance_fixed(&it%d));\n",
              decoder_depth);
      return true;
    }
    case CppType::Which::kString: {
      int temp_length = (*temporary_count)++;
      dprintf(fd, "  size_t length%d = 0;", temp_length);
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_validate(&it%d, "
              "CborValidateUtf8));\n",
              decoder_depth);
      dprintf(fd, "  if (cbor_value_is_length_known(&it%d)) {\n",
              decoder_depth);
      dprintf(fd,
              "    CBOR_RETURN_ON_ERROR(cbor_value_get_string_length(&it%d, "
              "&length%d));\n",
              decoder_depth, temp_length);
      dprintf(fd, "  } else {\n");
      dprintf(
          fd,
          "    CBOR_RETURN_ON_ERROR(cbor_value_calculate_string_length(&it%d, "
          "&length%d));\n",
          decoder_depth, temp_length);
      dprintf(fd, "  }\n");
      dprintf(fd, "  %s%sresize(length%d);\n", name.c_str(),
              member_accessor.c_str(), temp_length);
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_copy_text_string(&it%d, "
              "const_cast<char*>(%s%sdata()), &length%d, nullptr));\n",
              decoder_depth, name.c_str(), member_accessor.c_str(),
              temp_length);
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_value_advance(&it%d));\n",
              decoder_depth);
      return true;
    }
    case CppType::Which::kBytes: {
      int temp_length = (*temporary_count)++;
      dprintf(fd, "  size_t length%d = 0;", temp_length);
      dprintf(fd, "  if (cbor_value_is_length_known(&it%d)) {\n",
              decoder_depth);
      dprintf(fd,
              "    CBOR_RETURN_ON_ERROR(cbor_value_get_string_length(&it%d, "
              "&length%d));\n",
              decoder_depth, temp_length);
      dprintf(fd, "  } else {\n");
      dprintf(
          fd,
          "    CBOR_RETURN_ON_ERROR(cbor_value_calculate_string_length(&it%d, "
          "&length%d));\n",
          decoder_depth, temp_length);
      dprintf(fd, "  }\n");
      if (!cpp_type.bytes_type.fixed_size) {
        dprintf(fd, "  %s%sresize(length%d);\n", name.c_str(),
                member_accessor.c_str(), temp_length);
      } else {
        dprintf(fd, "  if (length%d < %d) {\n", temp_length,
                static_cast<int>(cpp_type.bytes_type.fixed_size.value()));
        dprintf(fd, "    return -CborErrorTooFewItems;\n");
        dprintf(fd, "  } else if (length%d > %d) {\n", temp_length,
                static_cast<int>(cpp_type.bytes_type.fixed_size.value()));
        dprintf(fd, "    return -CborErrorTooManyItems;\n");
        dprintf(fd, "  }\n");
      }
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_copy_byte_string(&it%d, "
              "const_cast<uint8_t*>(%s%sdata()), &length%d, nullptr));\n",
              decoder_depth, name.c_str(), member_accessor.c_str(),
              temp_length);
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_value_advance(&it%d));\n",
              decoder_depth);
      return true;
    }
    case CppType::Which::kVector: {
      dprintf(fd, "  if (cbor_value_get_type(&it%d) != CborArrayType) {\n",
              decoder_depth);
      dprintf(fd, "    return -1;\n");
      dprintf(fd, "  }\n");
      dprintf(fd, "  {\n");
      dprintf(fd, "  CborValue it%d;\n", decoder_depth + 1);
      dprintf(fd, "  size_t it%d_length = 0;\n", decoder_depth + 1);
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_get_array_length(&it%d, "
              "&it%d_length));\n",
              decoder_depth, decoder_depth + 1);
      if (cpp_type.vector_type.min_length !=
          CppType::Vector::kMinLengthUnbounded) {
        dprintf(fd, "  if (it%d_length < %d) {\n", decoder_depth + 1,
                cpp_type.vector_type.min_length);
        dprintf(fd, "    return -CborErrorTooFewItems;\n");
        dprintf(fd, "  }\n");
      }
      if (cpp_type.vector_type.max_length !=
          CppType::Vector::kMaxLengthUnbounded) {
        dprintf(fd, "  if (it%d_length > %d) {\n", decoder_depth + 1,
                cpp_type.vector_type.max_length);
        dprintf(fd, "    return -CborErrorTooManyItems;\n");
        dprintf(fd, "  }\n");
      }
      dprintf(fd, "  %s%sresize(it%d_length);\n", name.c_str(),
              member_accessor.c_str(), decoder_depth + 1);
      dprintf(
          fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_enter_container(&it%d, &it%d));\n",
          decoder_depth, decoder_depth + 1);
      dprintf(fd, "  for (auto i = %s%sbegin(); i != %s%send(); ++i) {\n",
              name.c_str(), member_accessor.c_str(), name.c_str(),
              member_accessor.c_str());
      if (!WriteDecoder(fd, "(*i)", ".", *cpp_type.vector_type.element_type,
                        decoder_depth + 1, temporary_count)) {
        return false;
      }
      dprintf(fd, "  }\n");
      dprintf(
          fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_leave_container(&it%d, &it%d));\n",
          decoder_depth, decoder_depth + 1);
      dprintf(fd, "  }\n");
      return true;
    }
    case CppType::Which::kEnum: {
      dprintf(fd,
              "  CBOR_RETURN_ON_ERROR(cbor_value_get_uint64(&it%d, "
              "reinterpret_cast<uint64_t*>(&%s)));\n",
              decoder_depth, name.c_str());
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_value_advance_fixed(&it%d));\n",
              decoder_depth);
      // TODO(btolsch): Validate against enum members.
      return true;
    }
    case CppType::Which::kStruct: {
      if (cpp_type.struct_type.key_type == CppType::Struct::KeyType::kMap) {
        return WriteMapDecoder(fd, name, member_accessor,
                               cpp_type.struct_type.members, decoder_depth + 1,
                               temporary_count);
      } else if (cpp_type.struct_type.key_type ==
                 CppType::Struct::KeyType::kArray) {
        return WriteArrayDecoder(fd, name, member_accessor,
                                 cpp_type.struct_type.members,
                                 decoder_depth + 1, temporary_count);
      }
    } break;
    case CppType::Which::kDiscriminatedUnion: {
      int temp_value_type = (*temporary_count)++;
      dprintf(fd, "  CborType type%d = cbor_value_get_type(&it%d);\n",
              temp_value_type, decoder_depth);
      bool first = true;
      for (const auto* x : cpp_type.discriminated_union.members) {
        if (first)
          first = false;
        else
          dprintf(fd, " else ");
        switch (x->which) {
          case CppType::Which::kUint64:
            dprintf(fd,
                    "  if (type%d == CborIntegerType && (it%d.flags & "
                    "CborIteratorFlag_NegativeInteger) == 0) {\n",
                    temp_value_type, decoder_depth);
            dprintf(fd, "  %s.which = decltype(%s)::Which::kUint64;\n",
                    name.c_str(), name.c_str());
            if (!WriteDecoder(fd, name + ".uint", ".", *x, decoder_depth,
                              temporary_count)) {
              return false;
            }
            break;
          case CppType::Which::kString: {
            dprintf(fd, "  if (type%d == CborTextStringType) {\n",
                    temp_value_type);
            dprintf(fd, "  %s.which = decltype(%s)::Which::kString;\n",
                    name.c_str(), name.c_str());
            std::string str_name = name + ".str";
            dprintf(fd, "  new (&%s) std::string();\n", str_name.c_str());
            if (!WriteDecoder(fd, str_name, ".", *x, decoder_depth,
                              temporary_count)) {
              return false;
            }
          } break;
          case CppType::Which::kBytes: {
            dprintf(fd, "  if (type%d == CborByteStringType) {\n",
                    temp_value_type);
            std::string bytes_name = name + ".bytes";
            dprintf(fd, "  %s.which = decltype(%s)::Which::kBytes;\n",
                    name.c_str(), name.c_str());
            dprintf(fd, "  new (&%s) std::vector<uint8_t>();\n",
                    bytes_name.c_str());
            if (!WriteDecoder(fd, bytes_name, ".", *x, decoder_depth,
                              temporary_count)) {
              return false;
            }
          } break;
          default:
            return false;
        }
        dprintf(fd, "  }\n");
      }
      dprintf(fd, " else { return -1; }\n");
      return true;
    }
    case CppType::Which::kTaggedType: {
      int temp_tag = (*temporary_count)++;
      dprintf(fd, "  uint64_t tag%d = 0;\n", temp_tag);
      dprintf(fd, "  cbor_value_get_tag(&it%d, &tag%d);\n", decoder_depth,
              temp_tag);
      dprintf(fd, "  if (tag%d != %" PRIu64 "ull) {\n", temp_tag,
              cpp_type.tagged_type.tag);
      dprintf(fd, "    return -1;\n");
      dprintf(fd, "  }\n");
      dprintf(fd, "  CBOR_RETURN_ON_ERROR(cbor_value_advance_fixed(&it%d));\n",
              decoder_depth);
      if (!WriteDecoder(fd, name, member_accessor,
                        *cpp_type.tagged_type.real_type, decoder_depth,
                        temporary_count)) {
        return false;
      }
      return true;
    }
    default:
      break;
  }
  return false;
}

// Writes the decoding function for the CBOR map with members in |members| to
// the file descriptor |fd|.  |name| is the C++ variable name that needs to be
// encoded.  |member_accessor| is either "." or "->" depending on whether |name|
// is a pointer type.  |decoder_depth| is used to independently name independent
// cbor decoders that need to be created.  |temporary_count| is used to ensure
// temporaries get unique names by appending an automatically incremented
// integer.
bool WriteMapDecoder(int fd,
                     const std::string& name,
                     const std::string& member_accessor,
                     const std::vector<CppType::Struct::CppMember>& members,
                     int decoder_depth,
                     int* temporary_count) {
  dprintf(fd, "  if (cbor_value_get_type(&it%d) != CborMapType) {\n",
          decoder_depth - 1);
  dprintf(fd, "    return -1;\n");
  dprintf(fd, "  }\n");
  dprintf(fd, "  CborValue it%d;\n", decoder_depth);
  dprintf(fd, "  size_t it%d_length = 0;\n", decoder_depth);
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_get_map_length(&it%d, "
          "&it%d_length));\n",
          decoder_depth - 1, decoder_depth);
  int optional_members = 0;
  for (const auto& member : members) {
    if (member.type->which == CppType::Which::kOptional) {
      ++optional_members;
    }
  }
  dprintf(fd, "  if (it%d_length != %d", decoder_depth,
          static_cast<int>(members.size()));
  for (int i = 0; i < optional_members; ++i) {
    dprintf(fd, " && it%d_length != %d", decoder_depth,
            static_cast<int>(members.size()) - i - 1);
  }
  dprintf(fd, ") {\n");
  dprintf(fd, "    return -1;\n");
  dprintf(fd, "  }\n");
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_enter_container(&it%d, &it%d));\n",
          decoder_depth - 1, decoder_depth);
  int member_pos = 0;
  for (const auto& x : members) {
    std::string cid = ToUnderscoreId(x.name);
    std::string fullname = name + member_accessor + cid;
    if (x.type->which == CppType::Which::kOptional) {
      // TODO(btolsch): This is wrong for the same reason as arrays, but will be
      // easier to handle when doing out-of-order keys.
      dprintf(fd, "  if (it%d_length > %d) {\n", decoder_depth, member_pos);

      if (x.integer_key.has_value()) {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(EXPECT_INT_KEY_CONSTANT(&it%d, %" PRIu64
                "));\n",
                decoder_depth, x.integer_key.value());
      } else {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(EXPECT_KEY_CONSTANT(&it%d, \"%s\"));\n",
                decoder_depth, x.name.c_str());
      }
      dprintf(fd, "    %s%shas_%s = true;\n", name.c_str(),
              member_accessor.c_str(), cid.c_str());
      if (!WriteDecoder(fd, fullname, ".", *x.type->optional_type,
                        decoder_depth, temporary_count)) {
        return false;
      }
      dprintf(fd, "  } else {\n");
      dprintf(fd, "    %s%shas_%s = false;\n", name.c_str(),
              member_accessor.c_str(), cid.c_str());
      dprintf(fd, "  }\n");
    } else {
      if (x.integer_key.has_value()) {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(EXPECT_INT_KEY_CONSTANT(&it%d, %" PRIu64
                "));\n",
                decoder_depth, x.integer_key.value());
      } else {
        dprintf(fd,
                "  CBOR_RETURN_ON_ERROR(EXPECT_KEY_CONSTANT(&it%d, \"%s\"));\n",
                decoder_depth, x.name.c_str());
      }
      if (!WriteDecoder(fd, fullname, ".", *x.type, decoder_depth,
                        temporary_count)) {
        return false;
      }
    }
    ++member_pos;
  }
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_leave_container(&it%d, &it%d));\n",
          decoder_depth - 1, decoder_depth);
  return true;
}

// Writes the decoding function for the CBOR array with members in |members| to
// the file descriptor |fd|.  |name| is the C++ variable name that needs to be
// encoded.  |member_accessor| is either "." or "->" depending on whether |name|
// is a pointer type.  |decoder_depth| is used to independently name independent
// cbor decoders that need to be created.  |temporary_count| is used to ensure
// temporaries get unique names by appending an automatically incremented
// integer.
bool WriteArrayDecoder(int fd,
                       const std::string& name,
                       const std::string& member_accessor,
                       const std::vector<CppType::Struct::CppMember>& members,
                       int decoder_depth,
                       int* temporary_count) {
  dprintf(fd, "  if (cbor_value_get_type(&it%d) != CborArrayType) {\n",
          decoder_depth - 1);
  dprintf(fd, "    return -1;\n");
  dprintf(fd, "  }\n");
  dprintf(fd, "  CborValue it%d;\n", decoder_depth);
  dprintf(fd, "  size_t it%d_length = 0;\n", decoder_depth);
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_get_array_length(&it%d, "
          "&it%d_length));\n",
          decoder_depth - 1, decoder_depth);
  int optional_members = 0;
  for (const auto& member : members) {
    if (member.type->which == CppType::Which::kOptional) {
      ++optional_members;
    }
  }
  dprintf(fd, "  if (it%d_length != %d", decoder_depth,
          static_cast<int>(members.size()));
  for (int i = 0; i < optional_members; ++i) {
    dprintf(fd, " && it%d_length != %d", decoder_depth,
            static_cast<int>(members.size()) - i - 1);
  }
  dprintf(fd, ") {\n");
  dprintf(fd, "    return -1;\n");
  dprintf(fd, "  }\n");
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_enter_container(&it%d, &it%d));\n",
          decoder_depth - 1, decoder_depth);
  int member_pos = 0;
  for (const auto& x : members) {
    std::string cid = ToUnderscoreId(x.name);
    std::string fullname = name + member_accessor + cid;
    if (x.type->which == CppType::Which::kOptional) {
      // TODO(btolsch): This only handles a single block of optionals and only
      // the ones present form a contiguous range from the start of the block.
      // However, we likely don't really need more than one optional for arrays
      // for the foreseeable future.  The proper approach would be to have a set
      // of possible types for the next element and a map for the member to
      // which each corresponds.
      dprintf(fd, "  if (it%d_length > %d) {\n", decoder_depth, member_pos);
      dprintf(fd, "    %s%shas_%s = true;\n", name.c_str(),
              member_accessor.c_str(), cid.c_str());
      if (!WriteDecoder(fd, fullname, ".", *x.type->optional_type,
                        decoder_depth, temporary_count)) {
        return false;
      }
      dprintf(fd, "  } else {\n");
      dprintf(fd, "    %s%shas_%s = false;\n", name.c_str(),
              member_accessor.c_str(), cid.c_str());
      dprintf(fd, "  }\n");
    } else {
      if (!WriteDecoder(fd, fullname, ".", *x.type, decoder_depth,
                        temporary_count)) {
        return false;
      }
    }
    ++member_pos;
  }
  dprintf(fd,
          "  CBOR_RETURN_ON_ERROR(cbor_value_leave_container(&it%d, &it%d));\n",
          decoder_depth - 1, decoder_depth);
  return true;
}

// Writes the equality operators for all structs.
bool WriteEqualityOperators(int fd, CppSymbolTable* table) {
  for (const auto& pair : table->cpp_type_map) {
    CppType* real_type = pair.second;
    if (real_type->which == CppType::Which::kStruct &&
        real_type->struct_type.key_type !=
            CppType::Struct::KeyType::kPlainGroup) {
      if (!WriteStructEqualityOperator(fd, *real_type)) {
        return false;
      }
    }
  }
  return true;
}

// Writes a decoder function definition for every type in |table| to the file
// descriptor |fd|.
bool WriteDecoders(int fd, CppSymbolTable* table) {
  if (!WriteTypeParserDefinition(fd, table)) {
    return false;
  }
  for (CppType* real_type : table->TypesWithId()) {
    const auto& name = real_type->name;
    int temporary_count = 0;
    if (real_type->which != CppType::Which::kStruct ||
        real_type->struct_type.key_type ==
            CppType::Struct::KeyType::kPlainGroup) {
      continue;
    }
    std::string cpp_name = ToCamelCase(name);
    dprintf(fd, "\nssize_t Decode%s(\n", cpp_name.c_str());
    dprintf(fd, "    const uint8_t* buffer,\n    size_t length,\n");
    dprintf(fd, "    %s* data) {\n", cpp_name.c_str());
    dprintf(fd, "  CborParser parser;\n");
    dprintf(fd, "  CborValue it0;\n");
    dprintf(
        fd,
        "  CBOR_RETURN_ON_ERROR(cbor_parser_init(buffer, length, 0, &parser, "
        "&it0));\n");
    if (real_type->struct_type.key_type == CppType::Struct::KeyType::kMap) {
      if (!WriteMapDecoder(fd, "data", "->", real_type->struct_type.members, 1,
                           &temporary_count)) {
        return false;
      }
    } else {
      if (!WriteArrayDecoder(fd, "data", "->", real_type->struct_type.members,
                             1, &temporary_count)) {
        return false;
      }
    }
    dprintf(
        fd,
        "  auto result = static_cast<ssize_t>(cbor_value_get_next_byte(&it0) - "
        "buffer);\n");
    dprintf(fd, "  return result;\n");
    dprintf(fd, "}\n");
  }
  return true;
}

// Converts the filename |header_filename| to a preprocessor token that can be
// used as a header guard macro name.
std::string ToHeaderGuard(const std::string& header_filename) {
  std::string result = header_filename;
  for (auto& c : result) {
    if (c == '/' || c == '.')
      c = '_';
    else
      c = toupper(c);
  }
  result += "_";
  return result;
}

bool WriteHeaderPrologue(int fd, const std::string& header_filename) {
  static const char prologue[] =
      R"(#ifndef %s
#define %s

#include <array>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

#include "third_party/tinycbor/src/src/cbor.h"

namespace openscreen {
namespace msgs {

enum CborErrors {
  kParserEOF = -CborErrorUnexpectedEOF,
};

class CborEncodeBuffer;
)";
  std::string header_guard = ToHeaderGuard(header_filename);
  dprintf(fd, prologue, header_guard.c_str(), header_guard.c_str());
  return true;
}

bool WriteHeaderEpilogue(int fd, const std::string& header_filename) {
  static const char epilogue[] = R"(
class TypeEnumValidator {
 public:
  static Type SafeCast(uint64_t type_id);
};

class CborEncodeBuffer {
 public:
  static constexpr size_t kDefaultInitialEncodeBufferSize = 250;
  static constexpr size_t kDefaultMaxEncodeBufferSize = 64000;

  CborEncodeBuffer();
  CborEncodeBuffer(size_t initial_size, size_t max_size);
  ~CborEncodeBuffer();

  bool Append(size_t length);
  bool ResizeBy(ssize_t length);
  bool SetType(const uint8_t encoded_id[], size_t size);

  const uint8_t* data() const { return data_.data(); }
  size_t size() const { return data_.size(); }

  uint8_t* Position() { return &data_[0] + position_; }
  size_t AvailableLength() { return data_.size() - position_; }

 private:
  size_t max_size_;
  size_t position_;
  std::vector<uint8_t> data_;
};

CborError ExpectKey(CborValue* it, const uint64_t key);
CborError ExpectKey(CborValue* it, const char* key, size_t key_length);

}  // namespace msgs
}  // namespace openscreen
#endif  // %s)";
  std::string header_guard = ToHeaderGuard(header_filename);
  dprintf(fd, epilogue, header_guard.c_str());
  return true;
}

bool WriteSourcePrologue(int fd, const std::string& header_filename) {
  static const char prologue[] =
      R"(#include "%s"

#include "third_party/tinycbor/src/src/utf8_p.h"
#include "util/osp_logging.h"

namespace openscreen {
namespace msgs {
namespace {

/*
 * Encoder-specific errors, so it's fine to check these even in the
 * parser.
 */
#define CBOR_RETURN_WHAT_ON_ERROR(stmt, what)                           \
  {                                                                     \
    CborError error = stmt;                                             \
    OSP_DCHECK_NE(error, CborErrorTooFewItems);                         \
    OSP_DCHECK_NE(error, CborErrorTooManyItems);                        \
    OSP_DCHECK_NE(error, CborErrorDataTooLarge);                        \
    if (error != CborNoError && error != CborErrorOutOfMemory)          \
      return what;                                                      \
  }
#define CBOR_RETURN_ON_ERROR_INTERNAL(stmt) \
  CBOR_RETURN_WHAT_ON_ERROR(stmt, error)
#define CBOR_RETURN_ON_ERROR(stmt) CBOR_RETURN_WHAT_ON_ERROR(stmt, -error)

#define EXPECT_KEY_CONSTANT(it, key) ExpectKey(it, key, sizeof(key) - 1)
#define EXPECT_INT_KEY_CONSTANT(it, key) ExpectKey(it, key)

bool IsValidUtf8(const std::string& s) {
  const uint8_t* buffer = reinterpret_cast<const uint8_t*>(s.data());
  const uint8_t* end = buffer + s.size();
  while (buffer < end) {
    // TODO(btolsch): This is an implementation detail of tinycbor so we should
    // eventually replace this call with our own utf8 validation.
    if (get_utf8(&buffer, end) == ~0u)
      return false;
  }
  return true;
}
}  // namespace

CborError ExpectKey(CborValue* it, const uint64_t key) {
  if  (!cbor_value_is_unsigned_integer(it))
    return CborErrorImproperValue;
  uint64_t observed_key;
  CBOR_RETURN_ON_ERROR_INTERNAL(cbor_value_get_uint64(it, &observed_key));
  if (observed_key != key)
    return CborErrorImproperValue;
  CBOR_RETURN_ON_ERROR_INTERNAL(cbor_value_advance_fixed(it));
  return CborNoError;
}

CborError ExpectKey(CborValue* it, const char* key, size_t key_length) {
  if(!cbor_value_is_text_string(it))
    return CborErrorImproperValue;
  size_t observed_length = 0;
  CBOR_RETURN_ON_ERROR_INTERNAL(
      cbor_value_get_string_length(it, &observed_length));
  if (observed_length != key_length)
    return CborErrorImproperValue;
  std::string observed_key(key_length, 0);
  CBOR_RETURN_ON_ERROR_INTERNAL(cbor_value_copy_text_string(
      it, const_cast<char*>(observed_key.data()), &observed_length, nullptr));
  if (observed_key != key)
    return CborErrorImproperValue;
  CBOR_RETURN_ON_ERROR_INTERNAL(cbor_value_advance(it));
  return CborNoError;
}

// static
constexpr size_t CborEncodeBuffer::kDefaultInitialEncodeBufferSize;

// static
constexpr size_t CborEncodeBuffer::kDefaultMaxEncodeBufferSize;

CborEncodeBuffer::CborEncodeBuffer()
    : max_size_(kDefaultMaxEncodeBufferSize),
      position_(0),
      data_(kDefaultInitialEncodeBufferSize) {}
CborEncodeBuffer::CborEncodeBuffer(size_t initial_size, size_t max_size)
    : max_size_(max_size), position_(0), data_(initial_size) {}
CborEncodeBuffer::~CborEncodeBuffer() = default;

bool CborEncodeBuffer::SetType(const uint8_t encoded_id[], size_t size) {
  if (this->AvailableLength() < size) {
    if (!this->ResizeBy(size)) {
      return false;
    }
  }
  memcpy(&data_[position_], encoded_id, size);
  position_ += size;
  return true;
}

bool CborEncodeBuffer::Append(size_t length) {
  if (length == 0)
    return false;
  if ((data_.size() + length) > max_size_) {
    length = max_size_ - data_.size();
    if (length == 0)
      return false;
  }
  size_t append_area = data_.size();
  data_.resize(append_area + length);
  position_ = append_area;
  return true;
}

bool CborEncodeBuffer::ResizeBy(ssize_t delta) {
  if (delta == 0)
    return true;
  if (delta < 0 && static_cast<size_t>(-delta) > data_.size())
    return false;
  if (delta > 0 && (data_.size() + delta) > max_size_)
    return false;
  data_.resize(data_.size() + delta);
  return true;
}

bool IsError(ssize_t x) {
  return x < 0;
}
)";
  dprintf(fd, prologue, header_filename.c_str());
  return true;
}

bool WriteSourceEpilogue(int fd) {
  static const char epilogue[] = R"(
}  // namespace msgs
}  // namespace openscreen)";
  dprintf(fd, epilogue);
  return true;
}