code_.SetValue("ENUM_NAME", NameWrappedInNameSpace(enum_def));
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
GenComment(enum_def.doc_comment);
- code_ += "{{ACCESS_TYPE}} enum {{ENUM_NAME}}: {{BASE_TYPE}}, Enum { ";
+ code_ += "{{ACCESS_TYPE}} enum {{ENUM_NAME}}: {{BASE_TYPE}}, Enum {";
Indent();
code_ += "{{ACCESS_TYPE}} typealias T = {{BASE_TYPE}}";
code_ +=
auto &value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
auto &enum_def = *value.type.enum_def;
- auto enum_val = enum_def.FindByValue(value.constant);
+ // Vector of enum defaults are always "[]" which never works.
+ const std::string constant = IsVector(value.type) ? "0" : value.constant;
+ auto enum_val = enum_def.FindByValue(constant);
std::string name;
if (enum_val) {
name = Name(*enum_val);
}
if (type.enum_def) {
- // The type.base_type can only be scalar, union, array or vector.
- // Table, struct or string can't have enum_def.
- // Default value of union and vector in NONE, NULL translated to "0".
- FLATBUFFERS_ASSERT(IsInteger(type.base_type) ||
- (type.base_type == BASE_TYPE_UNION) || IsVector(type) ||
- IsArray(type));
- if (IsVector(type)) {
- // Vector can't use initialization list.
- FLATBUFFERS_ASSERT(field->value.constant == "0");
+ // Verify the enum's type and default value.
+ const std::string &constant = field->value.constant;
+ if (type.base_type == BASE_TYPE_UNION) {
+ if (constant != "0") { return Error("Union defaults must be NONE"); }
+ } else if (IsVector(type)) {
+ if (constant != "0" && constant != "[]") {
+ return Error("Vector defaults may only be `[]`.");
+ }
+ } else if (IsArray(type)) {
+ if (constant != "0") {
+ return Error("Array defaults are not supported yet.");
+ }
} else {
- // All unions should have the NONE ("0") enum value.
- auto in_enum = field->IsOptional() ||
- type.enum_def->attributes.Lookup("bit_flags") ||
- type.enum_def->FindByValue(field->value.constant);
- if (false == in_enum)
- return Error("default value of " + field->value.constant +
- " for field " + name + " is not part of enum " +
- type.enum_def->name);
+ if (!IsInteger(type.base_type)) {
+ return Error("Enums must have integer base types");
+ }
+ // Optional and bitflags enums may have default constants that are not
+ // their specified variants.
+ if (!field->IsOptional() &&
+ type.enum_def->attributes.Lookup("bit_flags") == nullptr) {
+ if (type.enum_def->FindByValue(constant) == nullptr) {
+ return Error("default value of `" + constant + "` for " + "field `" +
+ name + "` is not part of enum `" + type.enum_def->name +
+ "`.");
+ }
+ }
}
}
cd ..
test_dir=`pwd`
alias fbc='${test_dir}/../flatc'
+shopt -s expand_aliases
cd ${swift_dir}/Tests/FlatBuffers.Test.SwiftTests
fbc --swift --gen-mutable --grpc --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs
XCTAssertEqual(defaults.someString, "some")
XCTAssertEqual(defaults.ints, [])
XCTAssertEqual(defaults.floats, [])
+ XCTAssertEqual(defaults.bools, [])
XCTAssertEqual(defaults.intsCount, 0)
XCTAssertEqual(defaults.floatsCount, 0)
+ XCTAssertEqual(defaults.abcsCount, 0)
+ XCTAssertEqual(defaults.boolsCount, 0)
}
func testFlatbuffersObjectAPI() {
XCTAssertEqual(defaults.someString, "some")
XCTAssertEqual(defaults.ints, [])
XCTAssertEqual(defaults.floats, [])
+ XCTAssertEqual(defaults.abcs, [])
+ XCTAssertEqual(defaults.bools, [])
let buffer = defaults.serialize(builder: &fbb, type: MoreDefaults.self)
let fDefaults = MoreDefaults.getRootAsMoreDefaults(bb: buffer)
XCTAssertEqual(fDefaults.floats, [])
XCTAssertEqual(fDefaults.intsCount, 0)
XCTAssertEqual(fDefaults.floatsCount, 0)
+ XCTAssertEqual(fDefaults.abcsCount, 0)
+ XCTAssertEqual(fDefaults.boolsCount, 0)
}
}
import FlatBuffers
/// Composite components of Monster color.
-public enum MyGame_Example_Color: UInt8, Enum {
+public enum MyGame_Example_Color: UInt8, Enum {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
public static var min: MyGame_Example_Color { return .red }
}
-public enum MyGame_Example_Race: Int8, Enum {
+public enum MyGame_Example_Race: Int8, Enum {
public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue }
public static var min: MyGame_Example_Race { return .none_ }
}
-public enum MyGame_Example_Any_: UInt8, Enum {
+public enum MyGame_Example_Any_: UInt8, Enum {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
}
}
}
-public enum MyGame_Example_AnyUniqueAliases: UInt8, Enum {
+public enum MyGame_Example_AnyUniqueAliases: UInt8, Enum {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
}
}
}
-public enum MyGame_Example_AnyAmbiguousAliases: UInt8, Enum {
+public enum MyGame_Example_AnyAmbiguousAliases: UInt8, Enum {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
import FlatBuffers
+public enum ABC: Int32, Enum {
+ public typealias T = Int32
+ public static var byteSize: Int { return MemoryLayout<Int32>.size }
+ public var value: Int32 { return self.rawValue }
+ case a = 0
+ case b = 1
+ case c = 2
+
+
+ public static var max: ABC { return .c }
+ public static var min: ABC { return .a }
+}
+
public struct MoreDefaults: FlatBufferObject, ObjectAPIPacker {
static func validateVersion() { FlatBuffersVersion_1_12_0() }
case floats = 6
case emptyString = 8
case someString = 10
+ case abcs = 12
+ case bools = 14
var v: Int32 { Int32(self.rawValue) }
var p: VOffset { self.rawValue }
}
public var emptyStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.emptyString.v) }
public var someString: String? { let o = _accessor.offset(VTOFFSET.someString.v); return o == 0 ? "some" : _accessor.string(at: o) }
public var someStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.someString.v) }
- public static func startMoreDefaults(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 4) }
+ public var abcsCount: Int32 { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func abcs(at index: Int32) -> ABC? { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? ABC.a : ABC(rawValue: _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4)) }
+ public var boolsCount: Int32 { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? 0 : _accessor.vector(count: o) }
+ public func bools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) }
+ public var bools: [Bool] { return _accessor.getVector(at: VTOFFSET.bools.v) ?? [] }
+ public static func startMoreDefaults(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 6) }
public static func addVectorOf(ints: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: ints, at: VTOFFSET.ints.p) }
public static func addVectorOf(floats: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: floats, at: VTOFFSET.floats.p) }
public static func add(emptyString: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: emptyString, at: VTOFFSET.emptyString.p) }
public static func add(someString: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: someString, at: VTOFFSET.someString.p) }
+ public static func addVectorOf(abcs: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: abcs, at: VTOFFSET.abcs.p) }
+ public static func addVectorOf(bools: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: bools, at: VTOFFSET.bools.p) }
public static func endMoreDefaults(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createMoreDefaults(
_ fbb: inout FlatBufferBuilder,
intsVectorOffset ints: Offset<UOffset> = Offset(),
floatsVectorOffset floats: Offset<UOffset> = Offset(),
emptyStringOffset emptyString: Offset<String> = Offset(),
- someStringOffset someString: Offset<String> = Offset()
+ someStringOffset someString: Offset<String> = Offset(),
+ abcsVectorOffset abcs: Offset<UOffset> = Offset(),
+ boolsVectorOffset bools: Offset<UOffset> = Offset()
) -> Offset<UOffset> {
let __start = MoreDefaults.startMoreDefaults(&fbb)
MoreDefaults.addVectorOf(ints: ints, &fbb)
MoreDefaults.addVectorOf(floats: floats, &fbb)
MoreDefaults.add(emptyString: emptyString, &fbb)
MoreDefaults.add(someString: someString, &fbb)
+ MoreDefaults.addVectorOf(abcs: abcs, &fbb)
+ MoreDefaults.addVectorOf(bools: bools, &fbb)
return MoreDefaults.endMoreDefaults(&fbb, start: __start)
}
__someString = Offset<String>()
}
+ let __abcs = builder.createVector(obj.abcs)
+ let __bools = builder.createVector(obj.bools)
let __root = MoreDefaults.startMoreDefaults(&builder)
MoreDefaults.addVectorOf(ints: __ints, &builder)
MoreDefaults.addVectorOf(floats: __floats, &builder)
MoreDefaults.add(emptyString: __emptyString, &builder)
MoreDefaults.add(someString: __someString, &builder)
+ MoreDefaults.addVectorOf(abcs: __abcs, &builder)
+ MoreDefaults.addVectorOf(bools: __bools, &builder)
return MoreDefaults.endMoreDefaults(&builder, start: __root)
}
}
public var floats: [Float32]
public var emptyString: String?
public var someString: String?
+ public var abcs: [ABC]
+ public var bools: [Bool]
public init(_ _t: inout MoreDefaults) {
ints = []
}
emptyString = _t.emptyString
someString = _t.someString
+ abcs = []
+ for index in 0..<_t.abcsCount {
+ abcs.append(_t.abcs(at: index)!)
+ }
+ bools = []
+ for index in 0..<_t.boolsCount {
+ bools.append(_t.bools(at: index))
+ }
}
public init() {
floats = []
emptyString = ""
someString = "some"
+ abcs = []
+ bools = []
}
public func serialize() -> ByteBuffer { return serialize(type: MoreDefaults.self) }
import FlatBuffers
-public enum optional_scalars_OptionalByte: Int8, Enum {
+public enum optional_scalars_OptionalByte: Int8, Enum {
public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue }
import FlatBuffers
-public enum Character: UInt8, Enum {
+public enum Character: UInt8, Enum {
public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue }
+enum ABC: int { A, B, C }
+
+
table MoreDefaults {
ints: [int] = [];
floats: [float] = [ ];
empty_string: string = "";
some_string: string = "some";
+ abcs: [ABC] = [];
+ bools: [bool] = [];
}
extern crate flatbuffers;
use self::flatbuffers::EndianScalar;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MIN_ABC: i32 = 0;
+#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
+pub const ENUM_MAX_ABC: i32 = 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_ABC: [ABC; 3] = [
+ ABC::A,
+ ABC::B,
+ ABC::C,
+];
+
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
+#[repr(transparent)]
+pub struct ABC(pub i32);
+#[allow(non_upper_case_globals)]
+impl ABC {
+ pub const A: Self = Self(0);
+ pub const B: Self = Self(1);
+ pub const C: Self = Self(2);
+
+ pub const ENUM_MIN: i32 = 0;
+ pub const ENUM_MAX: i32 = 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 std::fmt::Debug for ABC {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ if let Some(name) = self.variant_name() {
+ f.write_str(name)
+ } else {
+ f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
+ }
+ }
+}
+impl<'a> flatbuffers::Follow<'a> for ABC {
+ type Inner = Self;
+ #[inline]
+ fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
+ let b = flatbuffers::read_scalar_at::<i32>(buf, loc);
+ Self(b)
+ }
+}
+
+impl flatbuffers::Push for ABC {
+ type Output = ABC;
+ #[inline]
+ fn push(&self, dst: &mut [u8], _rest: &[u8]) {
+ flatbuffers::emplace_scalar::<i32>(dst, self.0);
+ }
+}
+
+impl flatbuffers::EndianScalar for ABC {
+ #[inline]
+ fn to_little_endian(self) -> Self {
+ let b = i32::to_le(self.0);
+ Self(b)
+ }
+ #[inline]
+ fn from_little_endian(self) -> Self {
+ let b = i32::from_le(self.0);
+ Self(b)
+ }
+}
+
+impl<'a> flatbuffers::Verifiable for ABC {
+ #[inline]
+ fn run_verifier(
+ v: &mut flatbuffers::Verifier, pos: usize
+ ) -> Result<(), flatbuffers::InvalidFlatbuffer> {
+ use self::flatbuffers::Verifiable;
+ i32::run_verifier(v, pos)
+ }
+}
+
+impl flatbuffers::SimpleToVerifyInSlice for ABC {}
pub enum MoreDefaultsOffset {}
#[derive(Copy, Clone, PartialEq)]
_fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,
args: &'args MoreDefaultsArgs<'args>) -> flatbuffers::WIPOffset<MoreDefaults<'bldr>> {
let mut builder = MoreDefaultsBuilder::new(_fbb);
+ if let Some(x) = args.bools { builder.add_bools(x); }
+ if let Some(x) = args.abcs { builder.add_abcs(x); }
if let Some(x) = args.some_string { builder.add_some_string(x); }
if let Some(x) = args.empty_string { builder.add_empty_string(x); }
if let Some(x) = args.floats { builder.add_floats(x); }
let x = self.some_string();
x.to_string()
};
+ let abcs = {
+ let x = self.abcs();
+ x.into_iter().collect()
+ };
+ let bools = {
+ let x = self.bools();
+ x.to_vec()
+ };
MoreDefaultsT {
ints,
floats,
empty_string,
some_string,
+ abcs,
+ bools,
}
}
pub const VT_INTS: flatbuffers::VOffsetT = 4;
pub const VT_FLOATS: flatbuffers::VOffsetT = 6;
pub const VT_EMPTY_STRING: flatbuffers::VOffsetT = 8;
pub const VT_SOME_STRING: flatbuffers::VOffsetT = 10;
+ pub const VT_ABCS: flatbuffers::VOffsetT = 12;
+ pub const VT_BOOLS: flatbuffers::VOffsetT = 14;
#[inline]
pub fn ints(&self) -> flatbuffers::Vector<'a, i32> {
pub fn some_string(&self) -> &'a str {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(MoreDefaults::VT_SOME_STRING, Some(&"some")).unwrap()
}
+ #[inline]
+ pub fn abcs(&self) -> flatbuffers::Vector<'a, ABC> {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, ABC>>>(MoreDefaults::VT_ABCS, Some(Default::default())).unwrap()
+ }
+ #[inline]
+ pub fn bools(&self) -> &'a [bool] {
+ self._tab.get::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'a, bool>>>(MoreDefaults::VT_BOOLS, Some(Default::default())).map(|v| v.safe_slice()).unwrap()
+ }
}
impl flatbuffers::Verifiable for MoreDefaults<'_> {
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, f32>>>(&"floats", Self::VT_FLOATS, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>(&"empty_string", Self::VT_EMPTY_STRING, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>(&"some_string", Self::VT_SOME_STRING, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, ABC>>>(&"abcs", Self::VT_ABCS, false)?
+ .visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, bool>>>(&"bools", Self::VT_BOOLS, false)?
.finish();
Ok(())
}
pub floats: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, f32>>>,
pub empty_string: Option<flatbuffers::WIPOffset<&'a str>>,
pub some_string: Option<flatbuffers::WIPOffset<&'a str>>,
+ pub abcs: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, ABC>>>,
+ pub bools: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, bool>>>,
}
impl<'a> Default for MoreDefaultsArgs<'a> {
#[inline]
floats: None,
empty_string: None,
some_string: None,
+ abcs: None,
+ bools: None,
}
}
}
self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_SOME_STRING, some_string);
}
#[inline]
+ pub fn add_abcs(&mut self, abcs: flatbuffers::WIPOffset<flatbuffers::Vector<'b , ABC>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_ABCS, abcs);
+ }
+ #[inline]
+ pub fn add_bools(&mut self, bools: flatbuffers::WIPOffset<flatbuffers::Vector<'b , bool>>) {
+ self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>(MoreDefaults::VT_BOOLS, bools);
+ }
+ #[inline]
pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>) -> MoreDefaultsBuilder<'a, 'b> {
let start = _fbb.start_table();
MoreDefaultsBuilder {
ds.field("floats", &self.floats());
ds.field("empty_string", &self.empty_string());
ds.field("some_string", &self.some_string());
+ ds.field("abcs", &self.abcs());
+ ds.field("bools", &self.bools());
ds.finish()
}
}
pub floats: Vec<f32>,
pub empty_string: String,
pub some_string: String,
+ pub abcs: Vec<ABC>,
+ pub bools: Vec<bool>,
}
impl Default for MoreDefaultsT {
fn default() -> Self {
floats: Default::default(),
empty_string: "".to_string(),
some_string: "some".to_string(),
+ abcs: Default::default(),
+ bools: Default::default(),
}
}
}
let x = &self.some_string;
_fbb.create_string(x)
});
+ let abcs = Some({
+ let x = &self.abcs;
+ _fbb.create_vector(x)
+ });
+ let bools = Some({
+ let x = &self.bools;
+ _fbb.create_vector(x)
+ });
MoreDefaults::create(_fbb, &MoreDefaultsArgs{
ints,
floats,
empty_string,
some_string,
+ abcs,
+ bools,
})
}
}
floats: Vec::new(),
empty_string: "".to_string(),
some_string: "some".to_string(),
+ abcs: Vec::new(),
+ bools: Vec::new(),
},
)
}
let m = flatbuffers::root::<MoreDefaults>(&[0; 4]).unwrap();
assert_eq!(m.ints().len(), 0);
assert_eq!(m.floats().len(), 0);
+ assert_eq!(m.abcs().len(), 0);
+ assert_eq!(m.bools().len(), 0);
assert_eq!(m.empty_string(), "");
assert_eq!(m.some_string(), "some");
}
schemas.push_back("table Monster { mana: [int] = []; }");
schemas.push_back("table Monster { mana: [uint] = [ ]; }");
schemas.push_back("table Monster { mana: [byte] = [\t\t\n]; }");
+ schemas.push_back("enum E:int{}table Monster{mana:[E]=[];}");
for (auto s = schemas.begin(); s < schemas.end(); s++) {
flatbuffers::Parser parser;
TEST_ASSERT(parser.Parse(s->c_str()));