diff --git a/samples/rust_generated/my_game/sample/vec_3_generated.rs b/samples/rust_generated/my_game/sample/vec_3_generated.rs index 5b2aca7fd1c..ec5b1ccd173 100644 --- a/samples/rust_generated/my_game/sample/vec_3_generated.rs +++ b/samples/rust_generated/my_game/sample/vec_3_generated.rs @@ -182,12 +182,21 @@ impl<'a> Vec3 { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct Vec3T { pub x: f32, pub y: f32, pub z: f32, } +impl Default for Vec3T { + fn default() -> Self { + Self { + x: 0.0, + y: 0.0, + z: 0.0, + } + } +} impl Vec3T { pub fn pack(&self) -> Vec3 { diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index 13a0241130c..3430a3486c6 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -3037,15 +3037,56 @@ class RustGenerator : public BaseGenerator { if (parser_.opts.generate_object_based_api) { // Struct declaration code_ += ""; - code_ += "#[derive(Debug, Clone, PartialEq, Default)]"; + code_ += "#[derive(Debug, Clone, PartialEq)]"; code_ += "{{ACCESS_TYPE}} struct {{STRUCT_OTY}} {"; ForAllStructFields(struct_def, [&](const FieldDef& field) { (void)field; // unused. code_ += "pub {{FIELD}}: {{FIELD_OTY}},"; }); code_ += "}"; + // Manual impl Default to avoid issues with arrays > 32 elements + // where #[derive(Default)] fails on older Rust versions. + code_ += "impl Default for {{STRUCT_OTY}} {"; + code_ += " fn default() -> Self {"; + code_ += " Self {"; + ForAllStructFields(struct_def, [&](const FieldDef& field) { + const auto full_type = GetFullType(field.value.type); + switch (full_type) { + case ftArrayOfBuiltin: { + // Use the correct zero literal for each element type: + // bool -> false, float/double -> 0.0, integers -> 0 + const auto elem_type = field.value.type.VectorType().base_type; + std::string zero; + if (elem_type == BASE_TYPE_BOOL) { + zero = "false"; + } else if (IsFloat(elem_type)) { + zero = "0.0"; + } else { + zero = "0"; + } + code_ += " {{FIELD}}: [" + zero + "; " + + NumToString(field.value.type.fixed_length) + "],"; + break; + } + case ftArrayOfEnum: + case ftArrayOfStruct: { + code_ += + " {{FIELD}}: ::flatbuffers::array_init(|_| " + "Default::default()),"; + break; + } + default: { + std::string default_value = + GetDefaultValue(field, kObject); + code_ += " {{FIELD}}: " + default_value + ","; + break; + } + } + }); + code_ += " }"; + code_ += " }"; + code_ += "}"; code_ += ""; - // The `pack` method that turns the native struct into its Flatbuffers // counterpart. code_ += "impl {{STRUCT_OTY}} {"; diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp index 4dda6a7d95d..f926aa5d4ff 100644 --- a/src/idl_gen_swift.cpp +++ b/src/idl_gen_swift.cpp @@ -282,9 +282,16 @@ class SwiftGenerator : public BaseGenerator { NumToString(field.value.type.VectorType().fixed_length); code_.SetValue("FIXEDLENGTH", fixed_length); - const auto vector_base_type = IsStruct(field.value.type.VectorType()) - ? (type + "()") - : SwiftConstant(field); + std::string vector_base_type; + if (IsStruct(field.value.type.VectorType())) { + vector_base_type = type + "()"; + } else if (IsBool(field.value.type.VectorType().base_type)) { + vector_base_type = "false"; + } else if (IsFloat(field.value.type.VectorType().base_type)) { + vector_base_type = "0.0"; + } else { + vector_base_type = SwiftConstant(field); + } code_ += "private var _{{FIELDVAR}}: InlineArray<{{FIXEDLENGTH}}, " + valueType + ">"; diff --git a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj index f869552ad07..c1e72331435 100644 --- a/tests/FlatBuffers.Test/FlatBuffers.Test.csproj +++ b/tests/FlatBuffers.Test/FlatBuffers.Test.csproj @@ -106,6 +106,9 @@ MyGame\Example\NestedStruct.cs + + MyGame\Example\LargeArrayStruct.cs + MyGame\Example\LongEnum.cs diff --git a/tests/MyGame/Example/LargeArrayStruct.cs b/tests/MyGame/Example/LargeArrayStruct.cs new file mode 100644 index 00000000000..3a38b02a0f2 --- /dev/null +++ b/tests/MyGame/Example/LargeArrayStruct.cs @@ -0,0 +1,150 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct LargeArrayStruct : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public LargeArrayStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public byte D(int j) { return __p.bb.Get(__p.bb_pos + 0 + j * 1); } + public const int DLength = 64; +#if ENABLE_SPAN_T + public Span GetDBytes() { return __p.bb.ToSpan(__p.bb_pos + 0, 64); } +#else + public ArraySegment? GetDBytes() { return __p.bb.ToArraySegment(__p.bb_pos + 0, 64);} +#endif + public void MutateD(int j, byte d) { __p.bb.Put(__p.bb_pos + 0 + j * 1, d); } + public float E(int j) { return __p.bb.GetFloat(__p.bb_pos + 64 + j * 4); } + public const int ELength = 64; +#if ENABLE_SPAN_T + public Span GetEBytes() { return System.Runtime.InteropServices.MemoryMarshal.Cast(__p.bb.ToSpan(__p.bb_pos + 64, 256)); } +#else + public ArraySegment? GetEBytes() { return __p.bb.ToArraySegment(__p.bb_pos + 64, 256);} +#endif + public void MutateE(int j, float e) { __p.bb.PutFloat(__p.bb_pos + 64 + j * 4, e); } + public bool F(int j) { return 0!=__p.bb.Get(__p.bb_pos + 320 + j * 1); } + public const int FLength = 64; +#if ENABLE_SPAN_T + public Span GetFBytes() { return System.Runtime.InteropServices.MemoryMarshal.Cast(__p.bb.ToSpan(__p.bb_pos + 320, 64)); } +#else + public ArraySegment? GetFBytes() { return __p.bb.ToArraySegment(__p.bb_pos + 320, 64);} +#endif + public void MutateF(int j, bool f) { __p.bb.Put(__p.bb_pos + 320 + j * 1, (byte)(f ? 1 : 0)); } + public MyGame.Example.NestedStruct G(int j) { return (new MyGame.Example.NestedStruct()).__assign(__p.bb_pos + 384 + j * 32, __p.bb); } + public MyGame.Example.TestEnum H(int j) { return (MyGame.Example.TestEnum)__p.bb.GetSbyte(__p.bb_pos + 2432 + j * 1); } + public const int HLength = 64; +#if ENABLE_SPAN_T + public Span GetHBytes() { return System.Runtime.InteropServices.MemoryMarshal.Cast(__p.bb.ToSpan(__p.bb_pos + 2432, 64)); } +#else + public ArraySegment? GetHBytes() { return __p.bb.ToArraySegment(__p.bb_pos + 2432, 64);} +#endif + public void MutateH(int j, MyGame.Example.TestEnum h) { __p.bb.PutSbyte(__p.bb_pos + 2432 + j * 1, (sbyte)h); } + + public static Offset CreateLargeArrayStruct(FlatBufferBuilder builder, byte[] D, float[] E, bool[] F, int[,] g_A, MyGame.Example.TestEnum[] g_B, MyGame.Example.TestEnum[,] g_C, long[,] g_D, MyGame.Example.TestEnum[] H) { + builder.Prep(8, 2496); + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.PutSbyte((sbyte)H[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.Prep(8, 32); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutLong(g_D[_idx0-1,_idx1-1]); + } + builder.Pad(5); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutSbyte((sbyte)g_C[_idx0-1,_idx1-1]); + } + builder.PutSbyte((sbyte)g_B[_idx0-1]); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutInt(g_A[_idx0-1,_idx1-1]); + } + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.PutBool(F[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.PutFloat(E[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.PutByte(D[_idx0-1]); + } + return new Offset(builder.Offset); + } + public LargeArrayStructT UnPack() { + var _o = new LargeArrayStructT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(LargeArrayStructT _o) { + _o.D = new byte[64]; + for (var _j = 0; _j < 64; ++_j) { _o.D[_j] = this.D(_j); } + _o.E = new float[64]; + for (var _j = 0; _j < 64; ++_j) { _o.E[_j] = this.E(_j); } + _o.F = new bool[64]; + for (var _j = 0; _j < 64; ++_j) { _o.F[_j] = this.F(_j); } + _o.G = new MyGame.Example.NestedStructT[64]; + for (var _j = 0; _j < 64; ++_j) { _o.G[_j] = this.G(_j).UnPack(); } + _o.H = new MyGame.Example.TestEnum[64]; + for (var _j = 0; _j < 64; ++_j) { _o.H[_j] = this.H(_j); } + } + public static Offset Pack(FlatBufferBuilder builder, LargeArrayStructT _o) { + if (_o == null) return default(Offset); + var _d = _o.D; + var _e = _o.E; + var _f = _o.F; + var _g_a = new int[64,2]; + for (var idx0 = 0; idx0 < 64; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_g_a[idx0,idx1] = _o.G[idx0].A[idx1];}} + var _g_b = new MyGame.Example.TestEnum[64]; + for (var idx0 = 0; idx0 < 64; ++idx0) {_g_b[idx0] = _o.G[idx0].B;} + var _g_c = new MyGame.Example.TestEnum[64,2]; + for (var idx0 = 0; idx0 < 64; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_g_c[idx0,idx1] = _o.G[idx0].C[idx1];}} + var _g_d = new long[64,2]; + for (var idx0 = 0; idx0 < 64; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_g_d[idx0,idx1] = _o.G[idx0].D[idx1];}} + var _h = _o.H; + return CreateLargeArrayStruct( + builder, + _d, + _e, + _f, + _g_a, + _g_b, + _g_c, + _g_d, + _h); + } +} + +public class LargeArrayStructT +{ + [Newtonsoft.Json.JsonProperty("d")] + public byte[] D { get; set; } + [Newtonsoft.Json.JsonProperty("e")] + public float[] E { get; set; } + [Newtonsoft.Json.JsonProperty("f")] + public bool[] F { get; set; } + [Newtonsoft.Json.JsonProperty("g")] + public MyGame.Example.NestedStructT[] G { get; set; } + [Newtonsoft.Json.JsonProperty("h")] + public MyGame.Example.TestEnum[] H { get; set; } + + public LargeArrayStructT() { + this.D = new byte[64]; + this.E = new float[64]; + this.F = new bool[64]; + this.G = new MyGame.Example.NestedStructT[64]; + this.H = new MyGame.Example.TestEnum[64]; + } +} + + +} diff --git a/tests/MyGame/Example/LargeArrayStruct.java b/tests/MyGame/Example/LargeArrayStruct.java new file mode 100644 index 00000000000..aa413062959 --- /dev/null +++ b/tests/MyGame/Example/LargeArrayStruct.java @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class LargeArrayStruct extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public LargeArrayStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int d(int j) { return bb.get(bb_pos + 0 + j * 1); } + public void mutateD(int j, int d) { bb.put(bb_pos + 0 + j * 1, (byte) d); } + public float e(int j) { return bb.getFloat(bb_pos + 64 + j * 4); } + public void mutateE(int j, float e) { bb.putFloat(bb_pos + 64 + j * 4, e); } + public boolean f(int j) { return 0!=bb.get(bb_pos + 320 + j * 1); } + public void mutateF(int j, boolean f) { bb.put(bb_pos + 320 + j * 1, (byte)(f ? 1 : 0)); } + public MyGame.Example.NestedStruct g(int j) { return g(new MyGame.Example.NestedStruct(), j); } + public MyGame.Example.NestedStruct g(MyGame.Example.NestedStruct obj, int j) { return obj.__assign(bb_pos + 384 + j * 32, bb); } + public byte h(int j) { return bb.get(bb_pos + 2432 + j * 1); } + public void mutateH(int j, byte h) { bb.put(bb_pos + 2432 + j * 1, h); } + + public static int createLargeArrayStruct(FlatBufferBuilder builder, int[] d, float[] e, boolean[] f, int[][] g_a, byte[] g_b, byte[][] g_c, long[][] g_d, byte[] h) { + builder.prep(8, 2496); + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.putByte(h[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.prep(8, 32); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putLong(g_d[_idx0-1][_idx1-1]); + } + builder.pad(5); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putByte(g_c[_idx0-1][_idx1-1]); + } + builder.putByte(g_b[_idx0-1]); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putInt(g_a[_idx0-1][_idx1-1]); + } + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.putBoolean(f[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.putFloat(e[_idx0-1]); + } + for (int _idx0 = 64; _idx0 > 0; _idx0--) { + builder.putByte((byte) d[_idx0-1]); + } + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public LargeArrayStruct get(int j) { return get(new LargeArrayStruct(), j); } + public LargeArrayStruct get(LargeArrayStruct obj, int j) { return obj.__assign(__element(j), bb); } + } + public LargeArrayStructT unpack() { + LargeArrayStructT _o = new LargeArrayStructT(); + unpackTo(_o); + return _o; + } + public void unpackTo(LargeArrayStructT _o) { + int[] _oD = _o.getD(); + for (int _j = 0; _j < 64; ++_j) { _oD[_j] = d(_j); } + float[] _oE = _o.getE(); + for (int _j = 0; _j < 64; ++_j) { _oE[_j] = e(_j); } + boolean[] _oF = _o.getF(); + for (int _j = 0; _j < 64; ++_j) { _oF[_j] = f(_j); } + MyGame.Example.NestedStructT[] _oG = _o.getG(); + for (int _j = 0; _j < 64; ++_j) { _oG[_j] = g(_j).unpack(); } + byte[] _oH = _o.getH(); + for (int _j = 0; _j < 64; ++_j) { _oH[_j] = h(_j); } + } + public static int pack(FlatBufferBuilder builder, LargeArrayStructT _o) { + if (_o == null) return 0; + int[] _d = _o.getD(); + float[] _e = _o.getE(); + boolean[] _f = _o.getF(); + int[][] _g_a = new int[64][2]; + for (int idx0 = 0; idx0 < 64; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_g_a[idx0][idx1] = _o.getG()[idx0].getA()[idx1];}} + byte[] _g_b = new byte[64]; + for (int idx0 = 0; idx0 < 64; ++idx0) {_g_b[idx0] = _o.getG()[idx0].getB();} + byte[][] _g_c = new byte[64][2]; + for (int idx0 = 0; idx0 < 64; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_g_c[idx0][idx1] = _o.getG()[idx0].getC()[idx1];}} + long[][] _g_d = new long[64][2]; + for (int idx0 = 0; idx0 < 64; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_g_d[idx0][idx1] = _o.getG()[idx0].getD()[idx1];}} + byte[] _h = _o.getH(); + return createLargeArrayStruct( + builder, + _d, + _e, + _f, + _g_a, + _g_b, + _g_c, + _g_d, + _h); + } +} + diff --git a/tests/MyGame/Example/LargeArrayStruct.py b/tests/MyGame/Example/LargeArrayStruct.py new file mode 100644 index 00000000000..d6de8196934 --- /dev/null +++ b/tests/MyGame/Example/LargeArrayStruct.py @@ -0,0 +1,226 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +from MyGame.Example.NestedStruct import NestedStruct +np = import_numpy() + +class LargeArrayStruct(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls) -> int: + return 2496 + + # LargeArrayStruct + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # LargeArrayStruct + def D(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Uint8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + i * 1)) for i in range(self.DLength())] + elif j >= 0 and j < self.DLength(): + return self._tab.Get(flatbuffers.number_types.Uint8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + j * 1)) + else: + return None + + # LargeArrayStruct + def DAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Uint8Flags, self._tab.Pos + 0, self.DLength()) + + # LargeArrayStruct + def DLength(self) -> int: + return 64 + + # LargeArrayStruct + def DIsNone(self) -> bool: + return False + + # LargeArrayStruct + def E(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(64 + i * 4)) for i in range(self.ELength())] + elif j >= 0 and j < self.ELength(): + return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(64 + j * 4)) + else: + return None + + # LargeArrayStruct + def EAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Float32Flags, self._tab.Pos + 64, self.ELength()) + + # LargeArrayStruct + def ELength(self) -> int: + return 64 + + # LargeArrayStruct + def EIsNone(self) -> bool: + return False + + # LargeArrayStruct + def F(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.BoolFlags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(320 + i * 1)) for i in range(self.FLength())] + elif j >= 0 and j < self.FLength(): + return self._tab.Get(flatbuffers.number_types.BoolFlags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(320 + j * 1)) + else: + return None + + # LargeArrayStruct + def FAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.BoolFlags, self._tab.Pos + 320, self.FLength()) + + # LargeArrayStruct + def FLength(self) -> int: + return 64 + + # LargeArrayStruct + def FIsNone(self) -> bool: + return False + + # LargeArrayStruct + def G(self, i: int) -> NestedStruct: + obj = NestedStruct() + obj.Init(self._tab.Bytes, self._tab.Pos + 384 + i * 32) + return obj + + # LargeArrayStruct + def GLength(self) -> int: + return 64 + + # LargeArrayStruct + def GIsNone(self) -> bool: + return False + + # LargeArrayStruct + def H(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2432 + i * 1)) for i in range(self.HLength())] + elif j >= 0 and j < self.HLength(): + return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2432 + j * 1)) + else: + return None + + # LargeArrayStruct + def HAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int8Flags, self._tab.Pos + 2432, self.HLength()) + + # LargeArrayStruct + def HLength(self) -> int: + return 64 + + # LargeArrayStruct + def HIsNone(self) -> bool: + return False + + +def CreateLargeArrayStruct(builder, d, e, f, g_a, g_b, g_c, g_d, h): + builder.Prep(8, 2496) + for _idx0 in range(64 , 0, -1): + builder.PrependInt8(h[_idx0-1]) + for _idx0 in range(64 , 0, -1): + builder.Prep(8, 32) + for _idx1 in range(2 , 0, -1): + builder.PrependInt64(g_d[_idx0-1][_idx1-1]) + builder.Pad(5) + for _idx1 in range(2 , 0, -1): + builder.PrependInt8(g_c[_idx0-1][_idx1-1]) + builder.PrependInt8(g_b[_idx0-1]) + for _idx1 in range(2 , 0, -1): + builder.PrependInt32(g_a[_idx0-1][_idx1-1]) + for _idx0 in range(64 , 0, -1): + builder.PrependBool(f[_idx0-1]) + for _idx0 in range(64 , 0, -1): + builder.PrependFloat32(e[_idx0-1]) + for _idx0 in range(64 , 0, -1): + builder.PrependUint8(d[_idx0-1]) + return builder.Offset() + +import MyGame.Example.NestedStruct +try: + from typing import List +except: + pass + +class LargeArrayStructT(object): + + # LargeArrayStructT + def __init__( + self, + d = None, + e = None, + f = None, + g = None, + h = None, + ): + self.d = d # type: Optional[List[int]] + self.e = e # type: Optional[List[float]] + self.f = f # type: Optional[List[bool]] + self.g = g # type: Optional[List[MyGame.Example.NestedStruct.NestedStructT]] + self.h = h # type: Optional[List[int]] + + @classmethod + def InitFromBuf(cls, buf, pos): + largeArrayStruct = LargeArrayStruct() + largeArrayStruct.Init(buf, pos) + return cls.InitFromObj(largeArrayStruct) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, largeArrayStruct): + x = LargeArrayStructT() + x._UnPack(largeArrayStruct) + return x + + # LargeArrayStructT + def _UnPack(self, largeArrayStruct): + if largeArrayStruct is None: + return + if not largeArrayStruct.DIsNone(): + if np is None: + self.d = [] + for i in range(largeArrayStruct.DLength()): + self.d.append(largeArrayStruct.D(i)) + else: + self.d = largeArrayStruct.DAsNumpy() + if not largeArrayStruct.EIsNone(): + if np is None: + self.e = [] + for i in range(largeArrayStruct.ELength()): + self.e.append(largeArrayStruct.E(i)) + else: + self.e = largeArrayStruct.EAsNumpy() + if not largeArrayStruct.FIsNone(): + if np is None: + self.f = [] + for i in range(largeArrayStruct.FLength()): + self.f.append(largeArrayStruct.F(i)) + else: + self.f = largeArrayStruct.FAsNumpy() + if not largeArrayStruct.GIsNone(): + self.g = [] + for i in range(largeArrayStruct.GLength()): + if largeArrayStruct.G(i) is None: + self.g.append(None) + else: + nestedStruct_ = MyGame.Example.NestedStruct.NestedStructT.InitFromObj(largeArrayStruct.G(i)) + self.g.append(nestedStruct_) + if not largeArrayStruct.HIsNone(): + if np is None: + self.h = [] + for i in range(largeArrayStruct.HLength()): + self.h.append(largeArrayStruct.H(i)) + else: + self.h = largeArrayStruct.HAsNumpy() + + # LargeArrayStructT + def Pack(self, builder): + return CreateLargeArrayStruct(builder, self.d, self.e, self.f, self.g.a, self.g.b, self.g.c, self.g.d, self.h) diff --git a/tests/MyGame/Example/LargeArrayStruct.pyi b/tests/MyGame/Example/LargeArrayStruct.pyi new file mode 100644 index 00000000000..755e857718d --- /dev/null +++ b/tests/MyGame/Example/LargeArrayStruct.pyi @@ -0,0 +1,60 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import typing +from MyGame.Example.NestedStruct import NestedStruct, NestedStructT +from MyGame.Example.TestEnum import TestEnum + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class LargeArrayStruct(object): + @classmethod + def SizeOf(cls) -> int: ... + + def Init(self, buf: bytes, pos: int) -> None: ... + def D(self, i: int) -> typing.List[int]: ... + def DAsNumpy(self) -> np.ndarray: ... + def DLength(self) -> int: ... + def DIsNone(self) -> bool: ... + def E(self, i: int) -> typing.List[float]: ... + def EAsNumpy(self) -> np.ndarray: ... + def ELength(self) -> int: ... + def EIsNone(self) -> bool: ... + def F(self, i: int) -> typing.List[bool]: ... + def FAsNumpy(self) -> np.ndarray: ... + def FLength(self) -> int: ... + def FIsNone(self) -> bool: ... + def G(self, i: int) -> NestedStruct | None: ... + def GLength(self) -> int: ... + def GIsNone(self) -> bool: ... + def H(self, i: int) -> typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]: ... + def HAsNumpy(self) -> np.ndarray: ... + def HLength(self) -> int: ... + def HIsNone(self) -> bool: ... +class LargeArrayStructT(object): + d: typing.List[int] + e: typing.List[float] + f: typing.List[bool] + g: typing.List[NestedStructT] + h: typing.List[typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]] + def __init__( + self, + d: typing.List[int] | None = ..., + e: typing.List[float] | None = ..., + f: typing.List[bool] | None = ..., + g: typing.List['NestedStructT'] | None = ..., + h: typing.List[typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]] | None = ..., + ) -> None: ... + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> LargeArrayStructT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> LargeArrayStructT: ... + @classmethod + def InitFromObj(cls, largeArrayStruct: LargeArrayStruct) -> LargeArrayStructT: ... + def _UnPack(self, largeArrayStruct: LargeArrayStruct) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... + +def CreateLargeArrayStruct(builder: flatbuffers.Builder, d: int, e: float, f: bool, g_a: int, g_b: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], g_c: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], g_d: int, h: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]) -> uoffset: ... + diff --git a/tests/MyGame/Example/LargeArrayStructT.java b/tests/MyGame/Example/LargeArrayStructT.java new file mode 100644 index 00000000000..44e9434504c --- /dev/null +++ b/tests/MyGame/Example/LargeArrayStructT.java @@ -0,0 +1,57 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class LargeArrayStructT { + private int[] d; + private float[] e; + private boolean[] f; + private MyGame.Example.NestedStructT[] g; + private byte[] h; + + public int[] getD() { return d; } + + public void setD(int[] d) { if (d != null && d.length == 64) this.d = d; } + + public float[] getE() { return e; } + + public void setE(float[] e) { if (e != null && e.length == 64) this.e = e; } + + public boolean[] getF() { return f; } + + public void setF(boolean[] f) { if (f != null && f.length == 64) this.f = f; } + + public MyGame.Example.NestedStructT[] getG() { return g; } + + public void setG(MyGame.Example.NestedStructT[] g) { if (g != null && g.length == 64) this.g = g; } + + public byte[] getH() { return h; } + + public void setH(byte[] h) { if (h != null && h.length == 64) this.h = h; } + + + public LargeArrayStructT() { + this.d = new int[64]; + this.e = new float[64]; + this.f = new boolean[64]; + this.g = new MyGame.Example.NestedStructT[64]; + this.h = new byte[64]; + } +} + diff --git a/tests/arrays_test.bfbs b/tests/arrays_test.bfbs index 77ed99f6684..24751b2ccf1 100644 Binary files a/tests/arrays_test.bfbs and b/tests/arrays_test.bfbs differ diff --git a/tests/arrays_test.fbs b/tests/arrays_test.fbs index 90cb0d7267c..00764b429dc 100644 --- a/tests/arrays_test.fbs +++ b/tests/arrays_test.fbs @@ -18,6 +18,14 @@ struct ArrayStruct{ f:[int64:2]; } +struct LargeArrayStruct { + d:[ubyte:64]; + e:[float:64]; + f:[bool:64]; + g:[NestedStruct:64]; + h:[TestEnum:64]; +} + table ArrayTable{ a:ArrayStruct; } diff --git a/tests/arrays_test.schema.json b/tests/arrays_test.schema.json index c33dc6caf43..088797062b9 100644 --- a/tests/arrays_test.schema.json +++ b/tests/arrays_test.schema.json @@ -59,6 +59,37 @@ }, "additionalProperties" : false }, + "MyGame_Example_LargeArrayStruct" : { + "type" : "object", + "properties" : { + "d" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255}, + "minItems": 64, + "maxItems": 64 + }, + "e" : { + "type" : "array", "items" : {"type" : "number"}, + "minItems": 64, + "maxItems": 64 + }, + "f" : { + "type" : "array", "items" : {"type" : "boolean"}, + "minItems": 64, + "maxItems": 64 + }, + "g" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_NestedStruct"}, + "minItems": 64, + "maxItems": 64 + }, + "h" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_TestEnum"}, + "minItems": 64, + "maxItems": 64 + } + }, + "additionalProperties" : false + }, "MyGame_Example_ArrayTable" : { "type" : "object", "properties" : { diff --git a/tests/arrays_test/arrays_test_generated.rs b/tests/arrays_test/arrays_test_generated.rs new file mode 100644 index 00000000000..f3fcaabe551 --- /dev/null +++ b/tests/arrays_test/arrays_test_generated.rs @@ -0,0 +1,921 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated + +extern crate alloc; + +#[allow(unused_imports, dead_code)] +pub mod my_game { + +extern crate alloc; +#[allow(unused_imports, dead_code)] +pub mod example { + +extern crate alloc; + +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_TEST_ENUM: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_TEST_ENUM: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_TEST_ENUM: [TestEnum; 3] = [ + TestEnum::A, + TestEnum::B, + TestEnum::C, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct TestEnum(pub i8); +#[allow(non_upper_case_globals)] +impl TestEnum { + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, + } + } +} +impl ::core::fmt::Debug for TestEnum { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> ::flatbuffers::Follow<'a> for TestEnum { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = unsafe { ::flatbuffers::read_scalar_at::(buf, loc) }; + Self(b) + } +} + +impl ::flatbuffers::Push for TestEnum { + type Output = TestEnum; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + unsafe { ::flatbuffers::emplace_scalar::(dst, self.0) }; + } +} + +impl ::flatbuffers::EndianScalar for TestEnum { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> ::flatbuffers::Verifiable for TestEnum { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + i8::run_verifier(v, pos) + } +} + +impl ::flatbuffers::SimpleToVerifyInSlice for TestEnum {} +// struct NestedStruct, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct NestedStruct(pub [u8; 32]); +impl Default for NestedStruct { + fn default() -> Self { + Self([0; 32]) + } +} +impl ::core::fmt::Debug for NestedStruct { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("NestedStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .finish() + } +} + +impl ::flatbuffers::SimpleToVerifyInSlice for NestedStruct {} +impl<'a> ::flatbuffers::Follow<'a> for NestedStruct { + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a NestedStruct>::follow(buf, loc) } + } +} +impl<'a> ::flatbuffers::Follow<'a> for &'a NestedStruct { + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} +impl<'b> ::flatbuffers::Push for NestedStruct { + type Output = NestedStruct; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const NestedStruct as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> ::flatbuffers::Verifiable for NestedStruct { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} + +impl<'a> NestedStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &[i32; 2], + b: TestEnum, + c: &[TestEnum; 2], + d: &[i64; 2], + ) -> Self { + let mut s = Self([0; 32]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s + } + + pub fn a(&'a self) -> ::flatbuffers::Array<'a, i32, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 0) } + } + + pub fn set_a(&mut self, items: &[i32; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; + } + + pub fn b(&self) -> TestEnum { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_b(&mut self, x: TestEnum) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn c(&'a self) -> ::flatbuffers::Array<'a, TestEnum, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 9) } + } + + pub fn set_c(&mut self, x: &[TestEnum; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(9), + 2, + ); + } + } + + pub fn d(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 16) } + } + + pub fn set_d(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 16, items) }; + } + + pub fn unpack(&self) -> NestedStructT { + NestedStructT { + a: self.a().into(), + b: self.b(), + c: self.c().into(), + d: self.d().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct NestedStructT { + pub a: [i32; 2], + pub b: TestEnum, + pub c: [TestEnum; 2], + pub d: [i64; 2], +} +impl Default for NestedStructT { + fn default() -> Self { + Self { + a: [0; 2], + b: TestEnum::A, + c: ::flatbuffers::array_init(|_| Default::default()), + d: [0; 2], + } + } +} +impl NestedStructT { + pub fn pack(&self) -> NestedStruct { + NestedStruct::new( + &self.a, + self.b, + &self.c, + &self.d, + ) + } +} + +// struct ArrayStruct, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct ArrayStruct(pub [u8; 160]); +impl Default for ArrayStruct { + fn default() -> Self { + Self([0; 160]) + } +} +impl ::core::fmt::Debug for ArrayStruct { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("ArrayStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .field("e", &self.e()) + .field("f", &self.f()) + .finish() + } +} + +impl ::flatbuffers::SimpleToVerifyInSlice for ArrayStruct {} +impl<'a> ::flatbuffers::Follow<'a> for ArrayStruct { + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a ArrayStruct>::follow(buf, loc) } + } +} +impl<'a> ::flatbuffers::Follow<'a> for &'a ArrayStruct { + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} +impl<'b> ::flatbuffers::Push for ArrayStruct { + type Output = ArrayStruct; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const ArrayStruct as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> ::flatbuffers::Verifiable for ArrayStruct { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} + +impl<'a> ArrayStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: f32, + b: &[i32; 15], + c: i8, + d: &[NestedStruct; 2], + e: i32, + f: &[i64; 2], + ) -> Self { + let mut s = Self([0; 160]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s.set_e(e); + s.set_f(f); + s + } + + pub fn a(&self) -> f32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: f32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn b(&'a self) -> ::flatbuffers::Array<'a, i32, 15> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 4) } + } + + pub fn set_b(&mut self, items: &[i32; 15]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 4, items) }; + } + + pub fn c(&self) -> i8 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[64..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_c(&mut self, x: i8) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[64..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn d(&'a self) -> ::flatbuffers::Array<'a, NestedStruct, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 72) } + } + + pub fn set_d(&mut self, x: &[NestedStruct; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(72), + 64, + ); + } + } + + pub fn e(&self) -> i32 { + let mut mem = ::core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + ::flatbuffers::EndianScalar::from_little_endian(unsafe { + ::core::ptr::copy_nonoverlapping( + self.0[136..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + ::core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_e(&mut self, x: i32) { + let x_le = ::flatbuffers::EndianScalar::to_little_endian(x); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + ::core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[136..].as_mut_ptr(), + ::core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn f(&'a self) -> ::flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 144) } + } + + pub fn set_f(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 144, items) }; + } + + pub fn unpack(&self) -> ArrayStructT { + ArrayStructT { + a: self.a(), + b: self.b().into(), + c: self.c(), + d: { let d = self.d(); ::flatbuffers::array_init(|i| d.get(i).unpack()) }, + e: self.e(), + f: self.f().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ArrayStructT { + pub a: f32, + pub b: [i32; 15], + pub c: i8, + pub d: [NestedStructT; 2], + pub e: i32, + pub f: [i64; 2], +} +impl Default for ArrayStructT { + fn default() -> Self { + Self { + a: 0.0, + b: [0; 15], + c: 0, + d: ::flatbuffers::array_init(|_| Default::default()), + e: 0, + f: [0; 2], + } + } +} +impl ArrayStructT { + pub fn pack(&self) -> ArrayStruct { + ArrayStruct::new( + self.a, + &self.b, + self.c, + &::flatbuffers::array_init(|i| self.d[i].pack()), + self.e, + &self.f, + ) + } +} + +// struct LargeArrayStruct, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct LargeArrayStruct(pub [u8; 384]); +impl Default for LargeArrayStruct { + fn default() -> Self { + Self([0; 384]) + } +} +impl ::core::fmt::Debug for LargeArrayStruct { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("LargeArrayStruct") + .field("d", &self.d()) + .field("e", &self.e()) + .field("f", &self.f()) + .finish() + } +} + +impl ::flatbuffers::SimpleToVerifyInSlice for LargeArrayStruct {} +impl<'a> ::flatbuffers::Follow<'a> for LargeArrayStruct { + type Inner = &'a LargeArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a LargeArrayStruct>::follow(buf, loc) } + } +} +impl<'a> ::flatbuffers::Follow<'a> for &'a LargeArrayStruct { + type Inner = &'a LargeArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} +impl<'b> ::flatbuffers::Push for LargeArrayStruct { + type Output = LargeArrayStruct; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const LargeArrayStruct as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> ::flatbuffers::Verifiable for LargeArrayStruct { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} + +impl<'a> LargeArrayStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + d: &[u8; 64], + e: &[f32; 64], + f: &[bool; 64], + ) -> Self { + let mut s = Self([0; 384]); + s.set_d(d); + s.set_e(e); + s.set_f(f); + s + } + + pub fn d(&'a self) -> ::flatbuffers::Array<'a, u8, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 0) } + } + + pub fn set_d(&mut self, items: &[u8; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; + } + + pub fn e(&'a self) -> ::flatbuffers::Array<'a, f32, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 64) } + } + + pub fn set_e(&mut self, items: &[f32; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 64, items) }; + } + + pub fn f(&'a self) -> ::flatbuffers::Array<'a, bool, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 320) } + } + + pub fn set_f(&mut self, items: &[bool; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 320, items) }; + } + + pub fn unpack(&self) -> LargeArrayStructT { + LargeArrayStructT { + d: self.d().into(), + e: self.e().into(), + f: self.f().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct LargeArrayStructT { + pub d: [u8; 64], + pub e: [f32; 64], + pub f: [bool; 64], +} +impl Default for LargeArrayStructT { + fn default() -> Self { + Self { + d: [0; 64], + e: [0.0; 64], + f: [false; 64], + } + } +} +impl LargeArrayStructT { + pub fn pack(&self) -> LargeArrayStruct { + LargeArrayStruct::new( + &self.d, + &self.e, + &self.f, + ) + } +} + +pub enum ArrayTableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct ArrayTable<'a> { + pub _tab: ::flatbuffers::Table<'a>, +} + +impl<'a> ::flatbuffers::Follow<'a> for ArrayTable<'a> { + type Inner = ArrayTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: unsafe { ::flatbuffers::Table::new(buf, loc) } } + } +} + +impl<'a> ArrayTable<'a> { + pub const VT_A: ::flatbuffers::VOffsetT = 4; + + #[inline] + pub unsafe fn init_from_table(table: ::flatbuffers::Table<'a>) -> Self { + ArrayTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: ::flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut ::flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ArrayTableArgs<'args> + ) -> ::flatbuffers::WIPOffset> { + let mut builder = ArrayTableBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> ArrayTableT { + let a = self.a().map(|x| { + x.unpack() + }); + ArrayTableT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option<&'a ArrayStruct> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ArrayTable::VT_A, None)} + } +} + +impl ::flatbuffers::Verifiable for ArrayTable<'_> { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.visit_table(pos)? + .visit_field::("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct ArrayTableArgs<'a> { + pub a: Option<&'a ArrayStruct>, +} +impl<'a> Default for ArrayTableArgs<'a> { + #[inline] + fn default() -> Self { + ArrayTableArgs { + a: None, + } + } +} + +pub struct ArrayTableBuilder<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> { + fbb_: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + start_: ::flatbuffers::WIPOffset<::flatbuffers::TableUnfinishedWIPOffset>, +} +impl<'a: 'b, 'b, A: ::flatbuffers::Allocator + 'a> ArrayTableBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: &ArrayStruct) { + self.fbb_.push_slot_always::<&ArrayStruct>(ArrayTable::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>) -> ArrayTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ArrayTableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> ::flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + ::flatbuffers::WIPOffset::new(o.value()) + } +} + +impl ::core::fmt::Debug for ArrayTable<'_> { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + let mut ds = f.debug_struct("ArrayTable"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct ArrayTableT { + pub a: Option, +} +impl Default for ArrayTableT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl ArrayTableT { + pub fn pack<'b, A: ::flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut ::flatbuffers::FlatBufferBuilder<'b, A> + ) -> ::flatbuffers::WIPOffset> { + let a_tmp = self.a.as_ref().map(|x| x.pack()); + let a = a_tmp.as_ref(); + ArrayTable::create(_fbb, &ArrayTableArgs{ + a, + }) + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `ArrayTable` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn root_as_array_table(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `ArrayTable` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_array_table_unchecked`. +pub fn size_prefixed_root_as_array_table(buf: &[u8]) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `ArrayTable` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn root_as_array_table_with_opts<'b, 'o>( + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `ArrayTable` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn size_prefixed_root_as_array_table_with_opts<'b, 'o>( + opts: &'o ::flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, ::flatbuffers::InvalidFlatbuffer> { + ::flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a ArrayTable and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `ArrayTable`. +pub unsafe fn root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable<'_> { + unsafe { ::flatbuffers::root_unchecked::(buf) } +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed ArrayTable and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `ArrayTable`. +pub unsafe fn size_prefixed_root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable<'_> { + unsafe { ::flatbuffers::size_prefixed_root_unchecked::(buf) } +} +pub const ARRAY_TABLE_IDENTIFIER: &str = "ARRT"; + +#[inline] +pub fn array_table_buffer_has_identifier(buf: &[u8]) -> bool { + ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, false) +} + +#[inline] +pub fn array_table_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + ::flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, true) +} + +pub const ARRAY_TABLE_EXTENSION: &str = "mon"; + +#[inline] +pub fn finish_array_table_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>( + fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, + root: ::flatbuffers::WIPOffset>) { + fbb.finish(root, Some(ARRAY_TABLE_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_array_table_buffer<'a, 'b, A: ::flatbuffers::Allocator + 'a>(fbb: &'b mut ::flatbuffers::FlatBufferBuilder<'a, A>, root: ::flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(ARRAY_TABLE_IDENTIFIER)); +} +} // pub mod Example +} // pub mod MyGame + diff --git a/tests/arrays_test/mod.rs b/tests/arrays_test/mod.rs index 129b3951996..844c0729d4e 100644 --- a/tests/arrays_test/mod.rs +++ b/tests/arrays_test/mod.rs @@ -10,6 +10,8 @@ pub mod my_game { pub use self::nested_struct_generated::*; mod array_struct_generated; pub use self::array_struct_generated::*; + mod large_array_struct_generated; + pub use self::large_array_struct_generated::*; mod array_table_generated; pub use self::array_table_generated::*; } // example diff --git a/tests/arrays_test/my_game/example/array_struct_generated.rs b/tests/arrays_test/my_game/example/array_struct_generated.rs index 031d8724f84..e7b2222ec3b 100644 --- a/tests/arrays_test/my_game/example/array_struct_generated.rs +++ b/tests/arrays_test/my_game/example/array_struct_generated.rs @@ -245,7 +245,7 @@ impl<'a> ArrayStruct { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct ArrayStructT { pub a: f32, pub b: [i32; 15], @@ -254,6 +254,18 @@ pub struct ArrayStructT { pub e: i32, pub f: [i64; 2], } +impl Default for ArrayStructT { + fn default() -> Self { + Self { + a: 0.0, + b: [0; 15], + c: 0, + d: ::flatbuffers::array_init(|_| Default::default()), + e: 0, + f: [0; 2], + } + } +} impl ArrayStructT { pub fn pack(&self) -> ArrayStruct { diff --git a/tests/arrays_test/my_game/example/large_array_struct_generated.rs b/tests/arrays_test/my_game/example/large_array_struct_generated.rs new file mode 100644 index 00000000000..cbcd021b8a6 --- /dev/null +++ b/tests/arrays_test/my_game/example/large_array_struct_generated.rs @@ -0,0 +1,223 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +use super::*; + +// struct LargeArrayStruct, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct LargeArrayStruct(pub [u8; 2496]); + +impl Default for LargeArrayStruct { + fn default() -> Self { + Self([0; 2496]) + } +} + +impl ::core::fmt::Debug for LargeArrayStruct { + fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { + f.debug_struct("LargeArrayStruct") + .field("d", &self.d()) + .field("e", &self.e()) + .field("f", &self.f()) + .field("g", &self.g()) + .field("h", &self.h()) + .finish() + } +} + +impl ::flatbuffers::SimpleToVerifyInSlice for LargeArrayStruct {} + +impl<'a> ::flatbuffers::Follow<'a> for LargeArrayStruct { + type Inner = &'a LargeArrayStruct; + + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { <&'a LargeArrayStruct>::follow(buf, loc) } + } +} + +impl<'a> ::flatbuffers::Follow<'a> for &'a LargeArrayStruct { + type Inner = &'a LargeArrayStruct; + + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + unsafe { ::flatbuffers::follow_cast_ref::(buf, loc) } + } +} + +impl<'b> ::flatbuffers::Push for LargeArrayStruct { + type Output = LargeArrayStruct; + + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = unsafe { ::core::slice::from_raw_parts(self as *const LargeArrayStruct as *const u8, ::size()) }; + dst.copy_from_slice(src); + } + + #[inline] + fn alignment() -> ::flatbuffers::PushAlignment { + ::flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> ::flatbuffers::Verifiable for LargeArrayStruct { + #[inline] + fn run_verifier( + v: &mut ::flatbuffers::Verifier, pos: usize + ) -> Result<(), ::flatbuffers::InvalidFlatbuffer> { + v.in_buffer::(pos) + } +} + +impl<'a> LargeArrayStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + d: &[u8; 64], + e: &[f32; 64], + f: &[bool; 64], + g: &[NestedStruct; 64], + h: &[TestEnum; 64], + ) -> Self { + let mut s = Self([0; 2496]); + s.set_d(d); + s.set_e(e); + s.set_f(f); + s.set_g(g); + s.set_h(h); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.LargeArrayStruct" + } + + pub fn d(&'a self) -> ::flatbuffers::Array<'a, u8, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 0) } + } + + pub fn set_d(&mut self, items: &[u8; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; + } + + pub fn e(&'a self) -> ::flatbuffers::Array<'a, f32, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 64) } + } + + pub fn set_e(&mut self, items: &[f32; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 64, items) }; + } + + pub fn f(&'a self) -> ::flatbuffers::Array<'a, bool, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 320) } + } + + pub fn set_f(&mut self, items: &[bool; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { ::flatbuffers::emplace_scalar_array(&mut self.0, 320, items) }; + } + + pub fn g(&'a self) -> ::flatbuffers::Array<'a, NestedStruct, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 384) } + } + + pub fn set_g(&mut self, x: &[NestedStruct; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(384), + 2048, + ); + } + } + + pub fn h(&'a self) -> ::flatbuffers::Array<'a, TestEnum, 64> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + use ::flatbuffers::Follow; + unsafe { ::flatbuffers::Array::follow(&self.0, 2432) } + } + + pub fn set_h(&mut self, x: &[TestEnum; 64]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + ::core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(2432), + 64, + ); + } + } + + pub fn unpack(&self) -> LargeArrayStructT { + LargeArrayStructT { + d: self.d().into(), + e: self.e().into(), + f: self.f().into(), + g: { let g = self.g(); ::flatbuffers::array_init(|i| g.get(i).unpack()) }, + h: self.h().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct LargeArrayStructT { + pub d: [u8; 64], + pub e: [f32; 64], + pub f: [bool; 64], + pub g: [NestedStructT; 64], + pub h: [TestEnum; 64], +} +impl Default for LargeArrayStructT { + fn default() -> Self { + Self { + d: [0; 64], + e: [0.0; 64], + f: [false; 64], + g: ::flatbuffers::array_init(|_| Default::default()), + h: ::flatbuffers::array_init(|_| Default::default()), + } + } +} + +impl LargeArrayStructT { + pub fn pack(&self) -> LargeArrayStruct { + LargeArrayStruct::new( + &self.d, + &self.e, + &self.f, + &::flatbuffers::array_init(|i| self.g[i].pack()), + &self.h, + ) + } +} diff --git a/tests/arrays_test/my_game/example/nested_struct_generated.rs b/tests/arrays_test/my_game/example/nested_struct_generated.rs index 65159143ed3..bf81a3cc353 100644 --- a/tests/arrays_test/my_game/example/nested_struct_generated.rs +++ b/tests/arrays_test/my_game/example/nested_struct_generated.rs @@ -179,13 +179,23 @@ impl<'a> NestedStruct { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct NestedStructT { pub a: [i32; 2], pub b: TestEnum, pub c: [TestEnum; 2], pub d: [i64; 2], } +impl Default for NestedStructT { + fn default() -> Self { + Self { + a: [0; 2], + b: TestEnum::A, + c: ::flatbuffers::array_init(|_| Default::default()), + d: [0; 2], + } + } +} impl NestedStructT { pub fn pack(&self) -> NestedStruct { diff --git a/tests/include_test1/my_game/other_name_space/unused_generated.rs b/tests/include_test1/my_game/other_name_space/unused_generated.rs index 12f7fa768bd..d19375f1783 100644 --- a/tests/include_test1/my_game/other_name_space/unused_generated.rs +++ b/tests/include_test1/my_game/other_name_space/unused_generated.rs @@ -116,10 +116,17 @@ impl<'a> Unused { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } +impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } +} impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/include_test1_generated.rs b/tests/include_test1_generated.rs index 708e8627b79..a0417f317b3 100644 --- a/tests/include_test1_generated.rs +++ b/tests/include_test1_generated.rs @@ -358,10 +358,17 @@ pub mod my_game { } } - #[derive(Debug, Clone, PartialEq, Default)] + #[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } + impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } + } impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/include_test2/my_game/other_name_space/unused_generated.rs b/tests/include_test2/my_game/other_name_space/unused_generated.rs index 12f7fa768bd..d19375f1783 100644 --- a/tests/include_test2/my_game/other_name_space/unused_generated.rs +++ b/tests/include_test2/my_game/other_name_space/unused_generated.rs @@ -116,10 +116,17 @@ impl<'a> Unused { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } +impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } +} impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/include_test2_generated.rs b/tests/include_test2_generated.rs index 708e8627b79..a0417f317b3 100644 --- a/tests/include_test2_generated.rs +++ b/tests/include_test2_generated.rs @@ -358,10 +358,17 @@ pub mod my_game { } } - #[derive(Debug, Clone, PartialEq, Default)] + #[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } + impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } + } impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/monster_test/my_game/example/ability_generated.rs b/tests/monster_test/my_game/example/ability_generated.rs index 7dd38491a7f..df8c8a6e6b5 100644 --- a/tests/monster_test/my_game/example/ability_generated.rs +++ b/tests/monster_test/my_game/example/ability_generated.rs @@ -160,11 +160,19 @@ impl<'a> Ability { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct AbilityT { pub id: u32, pub distance: u32, } +impl Default for AbilityT { + fn default() -> Self { + Self { + id: 0, + distance: 0, + } + } +} impl AbilityT { pub fn pack(&self) -> Ability { diff --git a/tests/monster_test/my_game/example/struct_of_structs_generated.rs b/tests/monster_test/my_game/example/struct_of_structs_generated.rs index f0d803f7a6f..8231985d18a 100644 --- a/tests/monster_test/my_game/example/struct_of_structs_generated.rs +++ b/tests/monster_test/my_game/example/struct_of_structs_generated.rs @@ -131,12 +131,21 @@ impl<'a> StructOfStructs { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct StructOfStructsT { pub a: AbilityT, pub b: TestT, pub c: AbilityT, } +impl Default for StructOfStructsT { + fn default() -> Self { + Self { + a: Default::default(), + b: Default::default(), + c: Default::default(), + } + } +} impl StructOfStructsT { pub fn pack(&self) -> StructOfStructs { diff --git a/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs b/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs index 1d8887816f5..3f972894b95 100644 --- a/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs +++ b/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs @@ -99,10 +99,17 @@ impl<'a> StructOfStructsOfStructs { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct StructOfStructsOfStructsT { pub a: StructOfStructsT, } +impl Default for StructOfStructsOfStructsT { + fn default() -> Self { + Self { + a: Default::default(), + } + } +} impl StructOfStructsOfStructsT { pub fn pack(&self) -> StructOfStructsOfStructs { diff --git a/tests/monster_test/my_game/example/test_generated.rs b/tests/monster_test/my_game/example/test_generated.rs index b7137647563..ae5341a28eb 100644 --- a/tests/monster_test/my_game/example/test_generated.rs +++ b/tests/monster_test/my_game/example/test_generated.rs @@ -149,11 +149,19 @@ impl<'a> Test { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct TestT { pub a: i16, pub b: i8, } +impl Default for TestT { + fn default() -> Self { + Self { + a: 0, + b: 0, + } + } +} impl TestT { pub fn pack(&self) -> Test { diff --git a/tests/monster_test/my_game/example/vec_3_generated.rs b/tests/monster_test/my_game/example/vec_3_generated.rs index 23ed7716180..53e7677eaf8 100644 --- a/tests/monster_test/my_game/example/vec_3_generated.rs +++ b/tests/monster_test/my_game/example/vec_3_generated.rs @@ -264,7 +264,7 @@ impl<'a> Vec3 { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct Vec3T { pub x: f32, pub y: f32, @@ -273,6 +273,18 @@ pub struct Vec3T { pub test2: Color, pub test3: TestT, } +impl Default for Vec3T { + fn default() -> Self { + Self { + x: 0.0, + y: 0.0, + z: 0.0, + test1: 0.0, + test2: Default::default(), + test3: Default::default(), + } + } +} impl Vec3T { pub fn pack(&self) -> Vec3 { diff --git a/tests/monster_test/my_game/other_name_space/unused_generated.rs b/tests/monster_test/my_game/other_name_space/unused_generated.rs index 12f7fa768bd..d19375f1783 100644 --- a/tests/monster_test/my_game/other_name_space/unused_generated.rs +++ b/tests/monster_test/my_game/other_name_space/unused_generated.rs @@ -116,10 +116,17 @@ impl<'a> Unused { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } +impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } +} impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/monster_test_serialize/my_game/example/ability_generated.rs b/tests/monster_test_serialize/my_game/example/ability_generated.rs index 0c866a58417..aba446c6d05 100644 --- a/tests/monster_test_serialize/my_game/example/ability_generated.rs +++ b/tests/monster_test_serialize/my_game/example/ability_generated.rs @@ -174,11 +174,19 @@ impl<'a> Ability { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct AbilityT { pub id: u32, pub distance: u32, } +impl Default for AbilityT { + fn default() -> Self { + Self { + id: 0, + distance: 0, + } + } +} impl AbilityT { pub fn pack(&self) -> Ability { diff --git a/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs index 053cb49e885..17b8d7cf0e6 100644 --- a/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs +++ b/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs @@ -146,12 +146,21 @@ impl<'a> StructOfStructs { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct StructOfStructsT { pub a: AbilityT, pub b: TestT, pub c: AbilityT, } +impl Default for StructOfStructsT { + fn default() -> Self { + Self { + a: Default::default(), + b: Default::default(), + c: Default::default(), + } + } +} impl StructOfStructsT { pub fn pack(&self) -> StructOfStructs { diff --git a/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs b/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs index 9172c8c5144..743baba2325 100644 --- a/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs +++ b/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs @@ -112,10 +112,17 @@ impl<'a> StructOfStructsOfStructs { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct StructOfStructsOfStructsT { pub a: StructOfStructsT, } +impl Default for StructOfStructsOfStructsT { + fn default() -> Self { + Self { + a: Default::default(), + } + } +} impl StructOfStructsOfStructsT { pub fn pack(&self) -> StructOfStructsOfStructs { diff --git a/tests/monster_test_serialize/my_game/example/test_generated.rs b/tests/monster_test_serialize/my_game/example/test_generated.rs index f34509cd95e..ed1bffa036c 100644 --- a/tests/monster_test_serialize/my_game/example/test_generated.rs +++ b/tests/monster_test_serialize/my_game/example/test_generated.rs @@ -163,11 +163,19 @@ impl<'a> Test { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct TestT { pub a: i16, pub b: i8, } +impl Default for TestT { + fn default() -> Self { + Self { + a: 0, + b: 0, + } + } +} impl TestT { pub fn pack(&self) -> Test { diff --git a/tests/monster_test_serialize/my_game/example/vec_3_generated.rs b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs index 193c4c48e80..3d2d6119924 100644 --- a/tests/monster_test_serialize/my_game/example/vec_3_generated.rs +++ b/tests/monster_test_serialize/my_game/example/vec_3_generated.rs @@ -282,7 +282,7 @@ impl<'a> Vec3 { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct Vec3T { pub x: f32, pub y: f32, @@ -291,6 +291,18 @@ pub struct Vec3T { pub test2: Color, pub test3: TestT, } +impl Default for Vec3T { + fn default() -> Self { + Self { + x: 0.0, + y: 0.0, + z: 0.0, + test1: 0.0, + test2: Default::default(), + test3: Default::default(), + } + } +} impl Vec3T { pub fn pack(&self) -> Vec3 { diff --git a/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs index 4d8a1b98602..99540dba58b 100644 --- a/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs +++ b/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs @@ -129,10 +129,17 @@ impl<'a> Unused { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct UnusedT { pub a: i32, } +impl Default for UnusedT { + fn default() -> Self { + Self { + a: 0, + } + } +} impl UnusedT { pub fn pack(&self) -> Unused { diff --git a/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs index c3c627b0bba..79034a6c1a5 100644 --- a/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs +++ b/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs @@ -149,11 +149,19 @@ impl<'a> StructInNestedNS { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct StructInNestedNST { pub a: i32, pub b: i32, } +impl Default for StructInNestedNST { + fn default() -> Self { + Self { + a: 0, + b: 0, + } + } +} impl StructInNestedNST { pub fn pack(&self) -> StructInNestedNS { diff --git a/tests/private_annotation_test/object_generated.rs b/tests/private_annotation_test/object_generated.rs index 07d44cfdeb3..05c18ac07d3 100644 --- a/tests/private_annotation_test/object_generated.rs +++ b/tests/private_annotation_test/object_generated.rs @@ -116,10 +116,17 @@ impl<'a> Object { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub(crate) struct ObjectT { pub value: i32, } +impl Default for ObjectT { + fn default() -> Self { + Self { + value: 0, + } + } +} impl ObjectT { pub fn pack(&self) -> Object { diff --git a/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs b/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs index 36bdc38f4e5..4d420023445 100644 --- a/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs +++ b/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs @@ -215,13 +215,23 @@ impl<'a> PossiblyReservedWords { } } -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct PossiblyReservedWordsT { pub follow_: f32, pub push_: f32, pub size: f32, pub alignment: f32, } +impl Default for PossiblyReservedWordsT { + fn default() -> Self { + Self { + follow_: 0.0, + push_: 0.0, + size: 0.0, + alignment: 0.0, + } + } +} impl PossiblyReservedWordsT { pub fn pack(&self) -> PossiblyReservedWords { diff --git a/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift b/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift index 644794f63d3..f9adfe3fc06 100644 --- a/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift +++ b/tests/swift/Tests/Flatbuffers/arrays_test_generated.swift @@ -275,6 +275,128 @@ public struct MyGame_Example_ArrayStruct_Mutable: FlatBufferStruct, FlatbuffersV } } +@available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) +public struct MyGame_Example_LargeArrayStruct: NativeStruct, FlatbuffersVectorInitializable, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_12_19() } + + private var _d: InlineArray<64, UInt8> + private var _e: InlineArray<64, Float32> + private var _f: InlineArray<64, Bool> + private var _g: InlineArray<64, MyGame_Example_NestedStruct> + private var _h: InlineArray<64, Int8> + + public init(_ bb: ByteBuffer, o: Int32) { + self = bb.read(def: Self.self, position: Int(o)) + } + + public init(d: InlineArray<64, UInt8>, e: InlineArray<64, Float32>, f: InlineArray<64, Bool>, g: InlineArray<64, MyGame_Example_NestedStruct>, h: InlineArray<64, Int8>) { + _d = d + _e = e + _f = f + _g = g + _h = h + } + + public init() { + _d = InlineArray(repeating: 0) + _e = InlineArray(repeating: 0.0) + _f = InlineArray(repeating: false) + _g = InlineArray(repeating: MyGame_Example_NestedStruct()) + _h = InlineArray(repeating: 0) + } + + public init(_ _t: borrowing MyGame_Example_LargeArrayStruct_Mutable) { + let _vd = _t.d + _d = InlineArray { _vd[$0] } + let _ve = _t.e + _e = InlineArray { _ve[$0] } + let _vf = _t.f + _f = InlineArray { _vf[$0] } + let _vg = _t.g + _g = InlineArray { _vg[$0].unpack() } + let _vh = _t.h + _h = InlineArray { _vh[$0].rawValue } + } + + public var d: InlineArray<64, UInt8> { _d } + public var e: InlineArray<64, Float32> { _e } + public var f: InlineArray<64, Bool> { _f } + public var g: InlineArray<64, MyGame_Example_NestedStruct> { _g } + public var h: InlineArray<64, MyGame_Example_TestEnum> { InlineArray { MyGame_Example_TestEnum(rawValue: _h[$0])! } } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_LargeArrayStruct.self) + } +} + +@available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) +extension MyGame_Example_LargeArrayStruct: Encodable { + enum CodingKeys: String, CodingKey { + case d = "d" + case e = "e" + case f = "f" + case g = "g" + case h = "h" + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var dContainer = container.nestedUnkeyedContainer(forKey: .d) + for index in d.startIndex.. { return _accessor.vector(at: 0, count: 64, size: 1) } + @discardableResult public func mutate(d: UInt8, at index: Int32) -> Bool { return _accessor.mutate(d, index: 0 + (index * 1)) } + public var e: FlatbufferVector { return _accessor.vector(at: 64, count: 64, size: 4) } + @discardableResult public func mutate(e: Float32, at index: Int32) -> Bool { return _accessor.mutate(e, index: 64 + (index * 4)) } + public var f: FlatbufferVector { return _accessor.vector(at: 320, count: 64, size: 1) } + @discardableResult public func mutate(f: Bool, at index: Int32) -> Bool { return _accessor.mutate(f, index: 320 + (index * 1)) } + public var g: FlatbufferVector { return _accessor.vector(at: 384, count: 64, size: 32) } + public var h: FlatbufferVector { return _accessor.vector(at: 2432, count: 64, size: 1) } + @discardableResult public func mutate(h: MyGame_Example_TestEnum, at index: Int32) -> Bool { return _accessor.mutate(h.rawValue, index: 2432 + (index * 1)) } + + public func unpack() -> MyGame_Example_LargeArrayStruct { + return MyGame_Example_LargeArrayStruct(self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_LargeArrayStruct?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_LargeArrayStruct) -> Offset { + return builder.create(struct: obj) + } +} + @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, *) public struct MyGame_Example_ArrayTable: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker {