Preserve relative order of structs and enums
diff --git a/gen/src/write.rs b/gen/src/write.rs
index fd2a815..b8d1dd4 100644
--- a/gen/src/write.rs
+++ b/gen/src/write.rs
@@ -9,7 +9,7 @@
     Var,
 };
 use proc_macro2::Ident;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
 
 pub(super) fn gen(apis: &[Api], types: &Types, opt: &Opt, header: bool) -> Vec<u8> {
     let mut out_file = OutFile::new(header, opt, types);
@@ -76,8 +76,22 @@
         }
     }
 
+    let mut structs_written = HashSet::new();
+    let mut toposorted_structs = out.types.toposorted_structs.iter();
     for api in apis {
         match api {
+            Api::Struct(strct) if !structs_written.contains(&strct.name.rust) => {
+                for next in &mut toposorted_structs {
+                    if !out.types.cxx.contains(&strct.name.rust) {
+                        out.next_section();
+                        write_struct(out, next);
+                    }
+                    structs_written.insert(&next.name.rust);
+                    if next.name.rust == strct.name.rust {
+                        break;
+                    }
+                }
+            }
             Api::Enum(enm) => {
                 out.next_section();
                 if out.types.cxx.contains(&enm.name.rust) {
@@ -96,13 +110,6 @@
         }
     }
 
-    for strct in &out.types.toposorted_structs {
-        out.next_section();
-        if !out.types.cxx.contains(&strct.name.rust) {
-            write_struct(out, strct);
-        }
-    }
-
     out.next_section();
     for api in apis {
         if let Api::TypeAlias(ety) = api {