bulk code format fix (#8707)

This commit is contained in:
Derek Bailey
2025-09-23 21:50:27 -07:00
committed by GitHub
parent 0e047869da
commit caf3b494db
559 changed files with 38871 additions and 31276 deletions

View File

@@ -57,10 +57,10 @@ let package = Package(
extension Array where Element == Package.Dependency {
static var dependencies: [Package.Dependency] {
#if os(Windows)
[]
[]
#else
// Test only Dependency
[.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")]
// Test only Dependency
[.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")]
#endif
}
}
@@ -68,13 +68,13 @@ extension Array where Element == Package.Dependency {
extension Array where Element == PackageDescription.Target.Dependency {
static var dependencies: [PackageDescription.Target.Dependency] {
#if os(Windows)
["FlatBuffers"]
["FlatBuffers"]
#else
// Test only Dependency
[
.product(name: "GRPC", package: "grpc-swift"),
"FlatBuffers",
]
// Test only Dependency
[
.product(name: "GRPC", package: "grpc-swift"),
"FlatBuffers",
]
#endif
}
}

View File

@@ -1,6 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_
#define FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_
@@ -9,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace com {
namespace fbs {
@@ -27,29 +26,24 @@ struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table {
VT_SOUND = 6,
VT_WEIGHT = 8
};
const ::flatbuffers::String *name() const {
return GetPointer<const ::flatbuffers::String *>(VT_NAME);
const ::flatbuffers::String* name() const {
return GetPointer<const ::flatbuffers::String*>(VT_NAME);
}
const ::flatbuffers::String *sound() const {
return GetPointer<const ::flatbuffers::String *>(VT_SOUND);
const ::flatbuffers::String* sound() const {
return GetPointer<const ::flatbuffers::String*>(VT_SOUND);
}
uint16_t weight() const {
return GetField<uint16_t>(VT_WEIGHT, 0);
}
bool Verify(::flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_SOUND) &&
uint16_t weight() const { return GetField<uint16_t>(VT_WEIGHT, 0); }
bool Verify(::flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) && VerifyOffset(verifier, VT_SOUND) &&
verifier.VerifyString(sound()) &&
VerifyField<uint16_t>(verifier, VT_WEIGHT, 2) &&
verifier.EndTable();
VerifyField<uint16_t>(verifier, VT_WEIGHT, 2) && verifier.EndTable();
}
};
struct AnimalBuilder {
typedef Animal Table;
::flatbuffers::FlatBufferBuilder &fbb_;
::flatbuffers::FlatBufferBuilder& fbb_;
::flatbuffers::uoffset_t start_;
void add_name(::flatbuffers::Offset<::flatbuffers::String> name) {
fbb_.AddOffset(Animal::VT_NAME, name);
@@ -60,8 +54,7 @@ struct AnimalBuilder {
void add_weight(uint16_t weight) {
fbb_.AddElement<uint16_t>(Animal::VT_WEIGHT, weight, 0);
}
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) {
start_ = fbb_.StartTable();
}
::flatbuffers::Offset<Animal> Finish() {
@@ -72,7 +65,7 @@ struct AnimalBuilder {
};
inline ::flatbuffers::Offset<Animal> CreateAnimal(
::flatbuffers::FlatBufferBuilder &_fbb,
::flatbuffers::FlatBufferBuilder& _fbb,
::flatbuffers::Offset<::flatbuffers::String> name = 0,
::flatbuffers::Offset<::flatbuffers::String> sound = 0,
uint16_t weight = 0) {
@@ -84,45 +77,37 @@ inline ::flatbuffers::Offset<Animal> CreateAnimal(
}
inline ::flatbuffers::Offset<Animal> CreateAnimalDirect(
::flatbuffers::FlatBufferBuilder &_fbb,
const char *name = nullptr,
const char *sound = nullptr,
uint16_t weight = 0) {
::flatbuffers::FlatBufferBuilder& _fbb, const char* name = nullptr,
const char* sound = nullptr, uint16_t weight = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto sound__ = sound ? _fbb.CreateString(sound) : 0;
return com::fbs::app::CreateAnimal(
_fbb,
name__,
sound__,
weight);
return com::fbs::app::CreateAnimal(_fbb, name__, sound__, weight);
}
inline const com::fbs::app::Animal *GetAnimal(const void *buf) {
inline const com::fbs::app::Animal* GetAnimal(const void* buf) {
return ::flatbuffers::GetRoot<com::fbs::app::Animal>(buf);
}
inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) {
inline const com::fbs::app::Animal* GetSizePrefixedAnimal(const void* buf) {
return ::flatbuffers::GetSizePrefixedRoot<com::fbs::app::Animal>(buf);
}
inline bool VerifyAnimalBuffer(
::flatbuffers::Verifier &verifier) {
inline bool VerifyAnimalBuffer(::flatbuffers::Verifier& verifier) {
return verifier.VerifyBuffer<com::fbs::app::Animal>(nullptr);
}
inline bool VerifySizePrefixedAnimalBuffer(
::flatbuffers::Verifier &verifier) {
inline bool VerifySizePrefixedAnimalBuffer(::flatbuffers::Verifier& verifier) {
return verifier.VerifySizePrefixedBuffer<com::fbs::app::Animal>(nullptr);
}
inline void FinishAnimalBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::FlatBufferBuilder& fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedAnimalBuffer(
::flatbuffers::FlatBufferBuilder &fbb,
::flatbuffers::FlatBufferBuilder& fbb,
::flatbuffers::Offset<com::fbs::app::Animal> root) {
fbb.FinishSizePrefixed(root);
}

View File

@@ -1,9 +1,9 @@
package com.flatbuffers.app
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.fbs.app.Animal
import com.google.flatbuffers.FlatBufferBuilder
import java.nio.ByteBuffer
@@ -27,14 +27,15 @@ class MainActivity : AppCompatActivity() {
private external fun createAnimalFromJNI(): ByteArray
// Create a "Cow" Animal flatbuffers from Kotlin
private fun createAnimalFromKotlin():Animal {
private fun createAnimalFromKotlin(): Animal {
val fb = FlatBufferBuilder(100)
val cowOffset = Animal.createAnimal(
builder = fb,
nameOffset = fb.createString("Cow"),
soundOffset = fb.createString("Moo"),
weight = 720u
)
val cowOffset =
Animal.createAnimal(
builder = fb,
nameOffset = fb.createString("Cow"),
soundOffset = fb.createString("Moo"),
weight = 720u,
)
fb.finish(cowOffset)
return Animal.getRootAsAnimal(fb.dataBuffer())
}

View File

@@ -2,83 +2,101 @@
package com.fbs.app
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.LongVector
import com.google.flatbuffers.StringVector
import com.google.flatbuffers.Struct
import com.google.flatbuffers.Table
import com.google.flatbuffers.UnionVector
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.sign
@Suppress("unused")
@kotlin.ExperimentalUnsignedTypes
class Animal : Table() {
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
fun __init(_i: Int, _bb: ByteBuffer) {
__reset(_i, _bb)
}
fun __assign(_i: Int, _bb: ByteBuffer): Animal {
__init(_i, _bb)
return this
}
val name: String?
get() {
val o = __offset(4)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
fun __assign(_i: Int, _bb: ByteBuffer) : Animal {
__init(_i, _bb)
return this
val nameAsByteBuffer: ByteBuffer
get() = __vector_as_bytebuffer(4, 1)
fun nameInByteBuffer(_bb: ByteBuffer): ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
val sound: String?
get() {
val o = __offset(6)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val name : String?
get() {
val o = __offset(4)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1)
fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1)
val sound : String?
get() {
val o = __offset(6)
return if (o != 0) {
__string(o + bb_pos)
} else {
null
}
}
val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
val weight : UShort
get() {
val o = __offset(8)
return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_25_2_10()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createAnimal(builder: FlatBufferBuilder, nameOffset: Int, soundOffset: Int, weight: UShort) : Int {
builder.startTable(3)
addSound(builder, soundOffset)
addName(builder, nameOffset)
addWeight(builder, weight)
return endAnimal(builder)
}
fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3)
fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0)
fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0)
fun addWeight(builder: FlatBufferBuilder, weight: UShort) = builder.addShort(2, weight.toShort(), 0)
fun endAnimal(builder: FlatBufferBuilder) : Int {
val o = builder.endTable()
return o
}
fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset)
fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset)
val soundAsByteBuffer: ByteBuffer
get() = __vector_as_bytebuffer(6, 1)
fun soundInByteBuffer(_bb: ByteBuffer): ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1)
val weight: UShort
get() {
val o = __offset(8)
return if (o != 0) bb.getShort(o + bb_pos).toUShort() else 0u
}
companion object {
fun validateVersion() = Constants.FLATBUFFERS_25_2_10()
fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal())
fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal {
_bb.order(ByteOrder.LITTLE_ENDIAN)
return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb))
}
fun createAnimal(
builder: FlatBufferBuilder,
nameOffset: Int,
soundOffset: Int,
weight: UShort,
): Int {
builder.startTable(3)
addSound(builder, soundOffset)
addName(builder, nameOffset)
addWeight(builder, weight)
return endAnimal(builder)
}
fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3)
fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0)
fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0)
fun addWeight(builder: FlatBufferBuilder, weight: UShort) =
builder.addShort(2, weight.toShort(), 0)
fun endAnimal(builder: FlatBufferBuilder): Int {
val o = builder.endTable()
return o
}
fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset)
fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) =
builder.finishSizePrefixed(offset)
}
}

View File

@@ -8,12 +8,12 @@ struct Bench {
inline void Add(int64_t value) { sum += value; }
virtual uint8_t *Encode(void *buf, int64_t &len) = 0;
virtual void *Decode(void *buf, int64_t len) = 0;
virtual int64_t Use(void *decoded) = 0;
virtual void Dealloc(void *decoded) = 0;
virtual uint8_t* Encode(void* buf, int64_t& len) = 0;
virtual void* Decode(void* buf, int64_t len) = 0;
virtual int64_t Use(void* decoded) = 0;
virtual void Dealloc(void* decoded) = 0;
int64_t sum = 0;
};
#endif // BENCHMARKS_CPP_BENCH_H_
#endif // BENCHMARKS_CPP_BENCH_H_

View File

@@ -1,6 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
#ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
#define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_
@@ -9,9 +8,9 @@
// Ensure the included flatbuffers.h is the same version as when this file was
// generated, otherwise it may not be compatible.
static_assert(FLATBUFFERS_VERSION_MAJOR == 24 &&
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
FLATBUFFERS_VERSION_MINOR == 12 &&
FLATBUFFERS_VERSION_REVISION == 23,
"Non-compatible flatbuffers version included");
namespace benchmarks_flatbuffers {
@@ -34,25 +33,16 @@ enum Enum : int16_t {
};
inline const Enum (&EnumValuesEnum())[3] {
static const Enum values[] = {
Enum_Apples,
Enum_Pears,
Enum_Bananas
};
static const Enum values[] = {Enum_Apples, Enum_Pears, Enum_Bananas};
return values;
}
inline const char * const *EnumNamesEnum() {
static const char * const names[4] = {
"Apples",
"Pears",
"Bananas",
nullptr
};
inline const char* const* EnumNamesEnum() {
static const char* const names[4] = {"Apples", "Pears", "Bananas", nullptr};
return names;
}
inline const char *EnumNameEnum(Enum e) {
inline const char* EnumNameEnum(Enum e) {
if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesEnum()[index];
@@ -67,12 +57,7 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
uint32_t length_;
public:
Foo()
: id_(0),
count_(0),
prefix_(0),
padding0__(0),
length_(0) {
Foo() : id_(0), count_(0), prefix_(0), padding0__(0), length_(0) {
(void)padding0__;
}
Foo(uint64_t _id, int16_t _count, int8_t _prefix, uint32_t _length)
@@ -83,18 +68,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS {
length_(flatbuffers::EndianScalar(_length)) {
(void)padding0__;
}
uint64_t id() const {
return flatbuffers::EndianScalar(id_);
}
int16_t count() const {
return flatbuffers::EndianScalar(count_);
}
int8_t prefix() const {
return flatbuffers::EndianScalar(prefix_);
}
uint32_t length() const {
return flatbuffers::EndianScalar(length_);
}
uint64_t id() const { return flatbuffers::EndianScalar(id_); }
int16_t count() const { return flatbuffers::EndianScalar(count_); }
int8_t prefix() const { return flatbuffers::EndianScalar(prefix_); }
uint32_t length() const { return flatbuffers::EndianScalar(length_); }
};
FLATBUFFERS_STRUCT_END(Foo, 16);
@@ -104,20 +81,17 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
int32_t time_;
float ratio_;
uint16_t size_;
int16_t padding0__; int32_t padding1__;
int16_t padding0__;
int32_t padding1__;
public:
Bar()
: parent_(),
time_(0),
ratio_(0),
size_(0),
padding0__(0),
padding1__(0) {
: parent_(), time_(0), ratio_(0), size_(0), padding0__(0), padding1__(0) {
(void)padding0__;
(void)padding1__;
}
Bar(const benchmarks_flatbuffers::Foo &_parent, int32_t _time, float _ratio, uint16_t _size)
Bar(const benchmarks_flatbuffers::Foo& _parent, int32_t _time, float _ratio,
uint16_t _size)
: parent_(_parent),
time_(flatbuffers::EndianScalar(_time)),
ratio_(flatbuffers::EndianScalar(_ratio)),
@@ -127,18 +101,10 @@ FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS {
(void)padding0__;
(void)padding1__;
}
const benchmarks_flatbuffers::Foo &parent() const {
return parent_;
}
int32_t time() const {
return flatbuffers::EndianScalar(time_);
}
float ratio() const {
return flatbuffers::EndianScalar(ratio_);
}
uint16_t size() const {
return flatbuffers::EndianScalar(size_);
}
const benchmarks_flatbuffers::Foo& parent() const { return parent_; }
int32_t time() const { return flatbuffers::EndianScalar(time_); }
float ratio() const { return flatbuffers::EndianScalar(ratio_); }
uint16_t size() const { return flatbuffers::EndianScalar(size_); }
};
FLATBUFFERS_STRUCT_END(Bar, 32);
@@ -150,34 +116,28 @@ struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_RATING = 8,
VT_POSTFIX = 10
};
const benchmarks_flatbuffers::Bar *sibling() const {
return GetStruct<const benchmarks_flatbuffers::Bar *>(VT_SIBLING);
const benchmarks_flatbuffers::Bar* sibling() const {
return GetStruct<const benchmarks_flatbuffers::Bar*>(VT_SIBLING);
}
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
const flatbuffers::String* name() const {
return GetPointer<const flatbuffers::String*>(VT_NAME);
}
double rating() const {
return GetField<double>(VT_RATING, 0.0);
}
uint8_t postfix() const {
return GetField<uint8_t>(VT_POSTFIX, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
double rating() const { return GetField<double>(VT_RATING, 0.0); }
uint8_t postfix() const { return GetField<uint8_t>(VT_POSTFIX, 0); }
bool Verify(flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<benchmarks_flatbuffers::Bar>(verifier, VT_SIBLING, 8) &&
VerifyOffset(verifier, VT_NAME) &&
verifier.VerifyString(name()) &&
VerifyOffset(verifier, VT_NAME) && verifier.VerifyString(name()) &&
VerifyField<double>(verifier, VT_RATING, 8) &&
VerifyField<uint8_t>(verifier, VT_POSTFIX, 1) &&
verifier.EndTable();
VerifyField<uint8_t>(verifier, VT_POSTFIX, 1) && verifier.EndTable();
}
};
struct FooBarBuilder {
typedef FooBar Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::FlatBufferBuilder& fbb_;
flatbuffers::uoffset_t start_;
void add_sibling(const benchmarks_flatbuffers::Bar *sibling) {
void add_sibling(const benchmarks_flatbuffers::Bar* sibling) {
fbb_.AddStruct(FooBar::VT_SIBLING, sibling);
}
void add_name(flatbuffers::Offset<flatbuffers::String> name) {
@@ -189,8 +149,7 @@ struct FooBarBuilder {
void add_postfix(uint8_t postfix) {
fbb_.AddElement<uint8_t>(FooBar::VT_POSTFIX, postfix, 0);
}
explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
explicit FooBarBuilder(flatbuffers::FlatBufferBuilder& _fbb) : fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBar> Finish() {
@@ -201,10 +160,9 @@ struct FooBarBuilder {
};
inline flatbuffers::Offset<FooBar> CreateFooBar(
flatbuffers::FlatBufferBuilder &_fbb,
const benchmarks_flatbuffers::Bar *sibling = nullptr,
flatbuffers::Offset<flatbuffers::String> name = 0,
double rating = 0.0,
flatbuffers::FlatBufferBuilder& _fbb,
const benchmarks_flatbuffers::Bar* sibling = nullptr,
flatbuffers::Offset<flatbuffers::String> name = 0, double rating = 0.0,
uint8_t postfix = 0) {
FooBarBuilder builder_(_fbb);
builder_.add_rating(rating);
@@ -215,18 +173,12 @@ inline flatbuffers::Offset<FooBar> CreateFooBar(
}
inline flatbuffers::Offset<FooBar> CreateFooBarDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const benchmarks_flatbuffers::Bar *sibling = nullptr,
const char *name = nullptr,
double rating = 0.0,
uint8_t postfix = 0) {
flatbuffers::FlatBufferBuilder& _fbb,
const benchmarks_flatbuffers::Bar* sibling = nullptr,
const char* name = nullptr, double rating = 0.0, uint8_t postfix = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
return benchmarks_flatbuffers::CreateFooBar(
_fbb,
sibling,
name__,
rating,
postfix);
return benchmarks_flatbuffers::CreateFooBar(_fbb, sibling, name__, rating,
postfix);
}
struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -237,49 +189,53 @@ struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_FRUIT = 8,
VT_LOCATION = 10
};
const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list() const {
return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *>(VT_LIST);
}
bool initialized() const {
return GetField<uint8_t>(VT_INITIALIZED, 0) != 0;
const flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*
list() const {
return GetPointer<const flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*>(VT_LIST);
}
bool initialized() const { return GetField<uint8_t>(VT_INITIALIZED, 0) != 0; }
benchmarks_flatbuffers::Enum fruit() const {
return static_cast<benchmarks_flatbuffers::Enum>(GetField<int16_t>(VT_FRUIT, 0));
return static_cast<benchmarks_flatbuffers::Enum>(
GetField<int16_t>(VT_FRUIT, 0));
}
const flatbuffers::String *location() const {
return GetPointer<const flatbuffers::String *>(VT_LOCATION);
const flatbuffers::String* location() const {
return GetPointer<const flatbuffers::String*>(VT_LOCATION);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffset(verifier, VT_LIST) &&
bool Verify(flatbuffers::Verifier& verifier) const {
return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_LIST) &&
verifier.VerifyVector(list()) &&
verifier.VerifyVectorOfTables(list()) &&
VerifyField<uint8_t>(verifier, VT_INITIALIZED, 1) &&
VerifyField<int16_t>(verifier, VT_FRUIT, 2) &&
VerifyOffset(verifier, VT_LOCATION) &&
verifier.VerifyString(location()) &&
verifier.EndTable();
verifier.VerifyString(location()) && verifier.EndTable();
}
};
struct FooBarContainerBuilder {
typedef FooBarContainer Table;
flatbuffers::FlatBufferBuilder &fbb_;
flatbuffers::FlatBufferBuilder& fbb_;
flatbuffers::uoffset_t start_;
void add_list(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list) {
void add_list(flatbuffers::Offset<flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>>
list) {
fbb_.AddOffset(FooBarContainer::VT_LIST, list);
}
void add_initialized(bool initialized) {
fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED, static_cast<uint8_t>(initialized), 0);
fbb_.AddElement<uint8_t>(FooBarContainer::VT_INITIALIZED,
static_cast<uint8_t>(initialized), 0);
}
void add_fruit(benchmarks_flatbuffers::Enum fruit) {
fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT, static_cast<int16_t>(fruit), 0);
fbb_.AddElement<int16_t>(FooBarContainer::VT_FRUIT,
static_cast<int16_t>(fruit), 0);
}
void add_location(flatbuffers::Offset<flatbuffers::String> location) {
fbb_.AddOffset(FooBarContainer::VT_LOCATION, location);
}
explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder& _fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
}
flatbuffers::Offset<FooBarContainer> Finish() {
@@ -290,8 +246,10 @@ struct FooBarContainerBuilder {
};
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
flatbuffers::FlatBufferBuilder &_fbb,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>> list = 0,
flatbuffers::FlatBufferBuilder& _fbb,
flatbuffers::Offset<flatbuffers::Vector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>>
list = 0,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
flatbuffers::Offset<flatbuffers::String> location = 0) {
@@ -304,47 +262,52 @@ inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainer(
}
inline flatbuffers::Offset<FooBarContainer> CreateFooBarContainerDirect(
flatbuffers::FlatBufferBuilder &_fbb,
const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>> *list = nullptr,
flatbuffers::FlatBufferBuilder& _fbb,
const std::vector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>*
list = nullptr,
bool initialized = false,
benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples,
const char *location = nullptr) {
auto list__ = list ? _fbb.CreateVector<flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list) : 0;
const char* location = nullptr) {
auto list__ =
list ? _fbb.CreateVector<
flatbuffers::Offset<benchmarks_flatbuffers::FooBar>>(*list)
: 0;
auto location__ = location ? _fbb.CreateString(location) : 0;
return benchmarks_flatbuffers::CreateFooBarContainer(
_fbb,
list__,
initialized,
fruit,
location__);
_fbb, list__, initialized, fruit, location__);
}
inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) {
inline const benchmarks_flatbuffers::FooBarContainer* GetFooBarContainer(
const void* buf) {
return flatbuffers::GetRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
}
inline const benchmarks_flatbuffers::FooBarContainer *GetSizePrefixedFooBarContainer(const void *buf) {
return flatbuffers::GetSizePrefixedRoot<benchmarks_flatbuffers::FooBarContainer>(buf);
inline const benchmarks_flatbuffers::FooBarContainer*
GetSizePrefixedFooBarContainer(const void* buf) {
return flatbuffers::GetSizePrefixedRoot<
benchmarks_flatbuffers::FooBarContainer>(buf);
}
inline bool VerifyFooBarContainerBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifyBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
inline bool VerifyFooBarContainerBuffer(flatbuffers::Verifier& verifier) {
return verifier.VerifyBuffer<benchmarks_flatbuffers::FooBarContainer>(
nullptr);
}
inline bool VerifySizePrefixedFooBarContainerBuffer(
flatbuffers::Verifier &verifier) {
return verifier.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(nullptr);
flatbuffers::Verifier& verifier) {
return verifier
.VerifySizePrefixedBuffer<benchmarks_flatbuffers::FooBarContainer>(
nullptr);
}
inline void FinishFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::FlatBufferBuilder& fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.Finish(root);
}
inline void FinishSizePrefixedFooBarContainerBuffer(
flatbuffers::FlatBufferBuilder &fbb,
flatbuffers::FlatBufferBuilder& fbb,
flatbuffers::Offset<benchmarks_flatbuffers::FooBarContainer> root) {
fbb.FinishSizePrefixed(root);
}

View File

@@ -8,16 +8,16 @@
#include "include/flatbuffers/flatbuffers.h"
struct StaticAllocator : public flatbuffers::Allocator {
explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {}
explicit StaticAllocator(uint8_t* buffer) : buffer_(buffer) {}
uint8_t *allocate(size_t) override { return buffer_; }
uint8_t* allocate(size_t) override { return buffer_; }
void deallocate(uint8_t *, size_t) override {}
void deallocate(uint8_t*, size_t) override {}
uint8_t *buffer_;
uint8_t* buffer_;
};
std::unique_ptr<Bench> NewFlatBuffersBench(
int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr);
int64_t initial_size = 1024, flatbuffers::Allocator* allocator = nullptr);
#endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_

View File

@@ -88,8 +88,8 @@ let benchmarks = {
Benchmark(
"Allocating ByteBuffer 1GB",
configuration: singleConfiguration)
{ benchmark in
configuration: singleConfiguration
) { benchmark in
let memory = UnsafeMutableRawPointer.allocate(
byteCount: 1_024_000_000,
alignment: 1)
@@ -108,7 +108,7 @@ let benchmarks = {
}
Benchmark("Strings 10") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.create(string: str10))
@@ -116,7 +116,7 @@ let benchmarks = {
}
Benchmark("Strings 100") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.create(string: str100))
@@ -124,7 +124,7 @@ let benchmarks = {
}
Benchmark("Vector 1 Bytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.createVector(bytes: bytes))
@@ -132,7 +132,7 @@ let benchmarks = {
}
Benchmark("Vector 1 Ints") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
blackHole(fb.createVector(ints))
@@ -140,7 +140,7 @@ let benchmarks = {
}
Benchmark("Vector 100 Ints") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(ints))
@@ -148,7 +148,7 @@ let benchmarks = {
}
Benchmark("Vector 100 Bytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(bytes))
@@ -156,7 +156,7 @@ let benchmarks = {
}
Benchmark("Vector 100 ContiguousBytes") { benchmark in
var fb = FlatBufferBuilder(initialSize: 1<<20)
var fb = FlatBufferBuilder(initialSize: 1 << 20)
benchmark.startMeasurement()
for i in benchmark.scaledIterations {
blackHole(fb.createVector(bytes: bytes))
@@ -165,8 +165,8 @@ let benchmarks = {
Benchmark(
"FlatBufferBuilder Add",
configuration: kiloConfiguration)
{ benchmark in
configuration: kiloConfiguration
) { benchmark in
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {
@@ -182,8 +182,8 @@ let benchmarks = {
Benchmark(
"FlatBufferBuilder Start table",
configuration: kiloConfiguration)
{ benchmark in
configuration: kiloConfiguration
) { benchmark in
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
benchmark.startMeasurement()
for _ in benchmark.scaledIterations {

View File

@@ -20,7 +20,7 @@ import PackageDescription
let package = Package(
name: "benchmarks",
platforms: [
.macOS(.v13),
.macOS(.v13)
],
dependencies: [
.package(path: "../.."),
@@ -37,6 +37,6 @@ let package = Package(
],
path: "Benchmarks/FlatbuffersBenchmarks",
plugins: [
.plugin(name: "BenchmarkPlugin", package: "package-benchmark"),
]),
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
])
])

View File

@@ -6,45 +6,54 @@ import subprocess
from cpt.packager import ConanMultiPackager
def get_branch():
try:
for line in subprocess.check_output("git branch", shell=True).decode().splitlines():
line = line.strip()
if line.startswith("*") and " (HEAD detached" not in line:
return line.replace("*", "", 1).strip()
return ""
except Exception:
pass
try:
for line in (
subprocess.check_output("git branch", shell=True).decode().splitlines()
):
line = line.strip()
if line.startswith("*") and " (HEAD detached" not in line:
return line.replace("*", "", 1).strip()
return ""
except Exception:
pass
return ""
def get_version():
version = get_branch()
match = re.search(r"v(\d+\.\d+\.\d+.*)", version)
if match:
return match.group(1)
return version
version = get_branch()
match = re.search(r"v(\d+\.\d+\.\d+.*)", version)
if match:
return match.group(1)
return version
def get_reference(username):
return "flatbuffers/{}@google/stable".format(get_version())
return "flatbuffers/{}@google/stable".format(get_version())
if __name__ == "__main__":
login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel")
username = os.getenv("CONAN_USERNAME", "google")
upload = os.getenv("CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers")
stable_branch_pattern = os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*")
test_folder = os.getenv("CPT_TEST_FOLDER", os.path.join("conan", "test_package"))
upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True)
login_username = os.getenv("CONAN_LOGIN_USERNAME", "aardappel")
username = os.getenv("CONAN_USERNAME", "google")
upload = os.getenv(
"CONAN_UPLOAD", "https://api.bintray.com/conan/aardappel/flatbuffers"
)
stable_branch_pattern = os.getenv(
"CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+.*"
)
test_folder = os.getenv(
"CPT_TEST_FOLDER", os.path.join("conan", "test_package")
)
upload_only_when_stable = os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", True)
builder = ConanMultiPackager(reference=get_reference(username),
username=username,
login_username=login_username,
upload=upload,
stable_branch_pattern=stable_branch_pattern,
upload_only_when_stable=upload_only_when_stable,
test_folder=test_folder)
builder.add_common_builds(pure_c=False)
builder.run()
builder = ConanMultiPackager(
reference=get_reference(username),
username=username,
login_username=login_username,
upload=upload,
stable_branch_pattern=stable_branch_pattern,
upload_only_when_stable=upload_only_when_stable,
test_folder=test_folder,
)
builder.add_common_builds(pure_c=False)
builder.run()

View File

@@ -1,21 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake
import os
from conans import CMake, ConanFile
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
bin_path = os.path.join("bin", "test_package")
self.run(bin_path, run_environment=True)
self.run("flatc --version", run_environment=True)
self.run("flathash fnv1_16 conan", run_environment=True)
def test(self):
bin_path = os.path.join("bin", "test_package")
self.run(bin_path, run_environment=True)
self.run("flatc --version", run_environment=True)
self.run("flathash fnv1_16 conan", run_environment=True)

View File

@@ -1,75 +1,83 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Conan recipe package for Google FlatBuffers
"""
"""Conan recipe package for Google FlatBuffers"""
import os
import shutil
from conans import ConanFile, CMake, tools
from conans import CMake, ConanFile, tools
class FlatbuffersConan(ConanFile):
name = "flatbuffers"
license = "Apache-2.0"
url = "https://github.com/google/flatbuffers"
homepage = "http://google.github.io/flatbuffers/"
author = "Wouter van Oortmerssen"
topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser")
description = "Memory Efficient Serialization Library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
exports = "LICENSE"
exports_sources = ["CMake/*", "include/*", "src/*", "grpc/*", "CMakeLists.txt", "conan/CMakeLists.txt"]
name = "flatbuffers"
license = "Apache-2.0"
url = "https://github.com/google/flatbuffers"
homepage = "http://google.github.io/flatbuffers/"
author = "Wouter van Oortmerssen"
topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser")
description = "Memory Efficient Serialization Library"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False], "fPIC": [True, False]}
default_options = {"shared": False, "fPIC": True}
generators = "cmake"
exports = "LICENSE"
exports_sources = [
"CMake/*",
"include/*",
"src/*",
"grpc/*",
"CMakeLists.txt",
"conan/CMakeLists.txt",
]
def source(self):
"""Wrap the original CMake file to call conan_basic_setup
"""
shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt")
shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt")
def source(self):
"""Wrap the original CMake file to call conan_basic_setup"""
shutil.move("CMakeLists.txt", "CMakeListsOriginal.txt")
shutil.move(os.path.join("conan", "CMakeLists.txt"), "CMakeLists.txt")
def config_options(self):
"""Remove fPIC option on Windows platform
"""
if self.settings.os == "Windows":
self.options.remove("fPIC")
def config_options(self):
"""Remove fPIC option on Windows platform"""
if self.settings.os == "Windows":
self.options.remove("fPIC")
def configure_cmake(self):
"""Create CMake instance and execute configure step
"""
cmake = CMake(self)
cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False
cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared
cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared
cmake.configure()
return cmake
def configure_cmake(self):
"""Create CMake instance and execute configure step"""
cmake = CMake(self)
cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False
cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared
cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared
cmake.configure()
return cmake
def build(self):
"""Configure, build and install FlatBuffers using CMake.
"""
cmake = self.configure_cmake()
cmake.build()
def build(self):
"""Configure, build and install FlatBuffers using CMake."""
cmake = self.configure_cmake()
cmake.build()
def package(self):
"""Copy Flatbuffers' artifacts to package folder
"""
cmake = self.configure_cmake()
cmake.install()
self.copy(pattern="LICENSE", dst="licenses")
self.copy(pattern="FindFlatBuffers.cmake", dst=os.path.join("lib", "cmake", "flatbuffers"), src="CMake")
self.copy(pattern="flathash*", dst="bin", src="bin")
self.copy(pattern="flatc*", dst="bin", src="bin")
if self.settings.os == "Windows" and self.options.shared:
if self.settings.compiler == "Visual Studio":
shutil.move(os.path.join(self.package_folder, "lib", "%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "%s.dll" % self.name))
elif self.settings.compiler == "gcc":
shutil.move(os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name))
def package(self):
"""Copy Flatbuffers' artifacts to package folder"""
cmake = self.configure_cmake()
cmake.install()
self.copy(pattern="LICENSE", dst="licenses")
self.copy(
pattern="FindFlatBuffers.cmake",
dst=os.path.join("lib", "cmake", "flatbuffers"),
src="CMake",
)
self.copy(pattern="flathash*", dst="bin", src="bin")
self.copy(pattern="flatc*", dst="bin", src="bin")
if self.settings.os == "Windows" and self.options.shared:
if self.settings.compiler == "Visual Studio":
shutil.move(
os.path.join(self.package_folder, "lib", "%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "%s.dll" % self.name),
)
elif self.settings.compiler == "gcc":
shutil.move(
os.path.join(self.package_folder, "lib", "lib%s.dll" % self.name),
os.path.join(self.package_folder, "bin", "lib%s.dll" % self.name),
)
def package_info(self):
"""Collect built libraries names and solve flatc path.
"""
self.cpp_info.libs = tools.collect_libs(self)
self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc")
def package_info(self):
"""Collect built libraries names and solve flatc path."""
self.cpp_info.libs = tools.collect_libs(self)
self.user_info.flatc = os.path.join(self.package_folder, "bin", "flatc")

View File

@@ -15,6 +15,7 @@
*/
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_my_game.sample_generated.dart' as my_game;
// Example how to use FlatBuffers to create and read binary buffers.
@@ -78,7 +79,8 @@ void builderTest() {
builder.finish(monsteroff);
if (verify(builder.buffer)) {
print(
"The FlatBuffer was successfully created with a builder and verified!");
"The FlatBuffer was successfully created with a builder and verified!",
);
}
}
@@ -94,7 +96,10 @@ void objectBuilderTest() {
name: 'Orc',
inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
color: my_game.Color.Red,
weapons: [my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), axe],
weapons: [
my_game.WeaponObjectBuilder(name: 'Sword', damage: 3),
axe,
],
equippedType: my_game.EquipmentTypeId.Weapon,
equipped: axe,
);
@@ -108,7 +113,8 @@ void objectBuilderTest() {
// Instead, we're going to access it right away (as if we just received it).
if (verify(buffer)) {
print(
"The FlatBuffer was successfully created with an object builder and verified!");
"The FlatBuffer was successfully created with an object builder and verified!",
);
}
}

View File

@@ -4,8 +4,8 @@
library my_game.sample;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Color {
final int value;
@@ -19,7 +19,7 @@ class Color {
return result;
}
static Color? _createOrNull(int? value) =>
static Color? _createOrNull(int? value) =>
value == null ? null : Color.fromValue(value);
static const int minValue = 0;
@@ -29,10 +29,7 @@ class Color {
static const Color Red = Color._(0);
static const Color Green = Color._(1);
static const Color Blue = Color._(2);
static const Map<int, Color> values = {
0: Red,
1: Green,
2: Blue};
static const Map<int, Color> values = {0: Red, 1: Green, 2: Blue};
static const fb.Reader<Color> reader = _ColorReader();
@@ -60,12 +57,14 @@ class EquipmentTypeId {
factory EquipmentTypeId.fromValue(int value) {
final result = values[value];
if (result == null) {
throw StateError('Invalid value $value for bit flag enum EquipmentTypeId');
throw StateError(
'Invalid value $value for bit flag enum EquipmentTypeId',
);
}
return result;
}
static EquipmentTypeId? _createOrNull(int? value) =>
static EquipmentTypeId? _createOrNull(int? value) =>
value == null ? null : EquipmentTypeId.fromValue(value);
static const int minValue = 0;
@@ -74,9 +73,7 @@ class EquipmentTypeId {
static const EquipmentTypeId NONE = EquipmentTypeId._(0);
static const EquipmentTypeId Weapon = EquipmentTypeId._(1);
static const Map<int, EquipmentTypeId> values = {
0: NONE,
1: Weapon};
static const Map<int, EquipmentTypeId> values = {0: NONE, 1: Weapon};
static const fb.Reader<EquipmentTypeId> reader = _EquipmentTypeIdReader();
@@ -122,8 +119,7 @@ class _Vec3Reader extends fb.StructReader<Vec3> {
int get size => 12;
@override
Vec3 createObject(fb.BufferContext bc, int offset) =>
Vec3._(bc, offset);
Vec3 createObject(fb.BufferContext bc, int offset) => Vec3._(bc, offset);
}
class Vec3Builder {
@@ -137,7 +133,6 @@ class Vec3Builder {
fbBuilder.putFloat32(x);
return fbBuilder.offset;
}
}
class Vec3ObjectBuilder extends fb.ObjectBuilder {
@@ -145,14 +140,10 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
final double _y;
final double _z;
Vec3ObjectBuilder({
required double x,
required double y,
required double z,
})
: _x = x,
_y = y,
_z = z;
Vec3ObjectBuilder({required double x, required double y, required double z})
: _x = x,
_y = y,
_z = z;
/// Finish building, and store into the [fbBuilder].
@override
@@ -171,6 +162,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class Monster {
Monster._(this._bc, this._bcOffset);
factory Monster(List<int> bytes) {
@@ -186,18 +178,30 @@ class Monster {
Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
List<int>? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon>? get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18);
EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20));
String? get name =>
const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
List<int>? get inventory =>
const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14);
Color get color =>
Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon>? get weapons => const fb.ListReader<Weapon>(
Weapon.reader,
).vTableGetNullable(_bc, _bcOffset, 18);
EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(
const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20),
);
dynamic get equipped {
switch (equippedType?.value) {
case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default: return null;
case 1:
return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default:
return null;
}
}
List<Vec3>? get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24);
List<Vec3>? get path => const fb.ListReader<Vec3>(
Vec3.reader,
).vTableGetNullable(_bc, _bcOffset, 24);
@override
String toString() {
@@ -209,8 +213,8 @@ class _MonsterReader extends fb.TableReader<Monster> {
const _MonsterReader();
@override
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
}
class MonsterBuilder {
@@ -226,38 +230,47 @@ class MonsterBuilder {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
int addColor(Color? color) {
fbBuilder.addInt8(6, color?.value);
return fbBuilder.offset;
}
int addWeaponsOffset(int? offset) {
fbBuilder.addOffset(7, offset);
return fbBuilder.offset;
}
int addEquippedType(EquipmentTypeId? equippedType) {
fbBuilder.addUint8(8, equippedType?.value);
return fbBuilder.offset;
}
int addEquippedOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
int addPathOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
@@ -291,29 +304,34 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
EquipmentTypeId? equippedType,
dynamic equipped,
List<Vec3ObjectBuilder>? path,
})
: _pos = pos,
_mana = mana,
_hp = hp,
_name = name,
_inventory = inventory,
_color = color,
_weapons = weapons,
_equippedType = equippedType,
_equipped = equipped,
_path = path;
}) : _pos = pos,
_mana = mana,
_hp = hp,
_name = name,
_inventory = inventory,
_color = color,
_weapons = weapons,
_equippedType = equippedType,
_equipped = equipped,
_path = path;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? nameOffset = _name == null ? null
final int? nameOffset = _name == null
? null
: fbBuilder.writeString(_name!);
final int? inventoryOffset = _inventory == null ? null
final int? inventoryOffset = _inventory == null
? null
: fbBuilder.writeListUint8(_inventory!);
final int? weaponsOffset = _weapons == null ? null
: fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList());
final int? weaponsOffset = _weapons == null
? null
: fbBuilder.writeList(
_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList(),
);
final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
final int? pathOffset = _path == null ? null
final int? pathOffset = _path == null
? null
: fbBuilder.writeListOfStructs(_path!);
fbBuilder.startTable(10);
if (_pos != null) {
@@ -339,6 +357,7 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class Weapon {
Weapon._(this._bc, this._bcOffset);
factory Weapon(List<int> bytes) {
@@ -351,7 +370,8 @@ class Weapon {
final fb.BufferContext _bc;
final int _bcOffset;
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
String? get name =>
const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0);
@override
@@ -364,8 +384,7 @@ class _WeaponReader extends fb.TableReader<Weapon> {
const _WeaponReader();
@override
Weapon createObject(fb.BufferContext bc, int offset) =>
Weapon._(bc, offset);
Weapon createObject(fb.BufferContext bc, int offset) => Weapon._(bc, offset);
}
class WeaponBuilder {
@@ -381,6 +400,7 @@ class WeaponBuilder {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int addDamage(int? damage) {
fbBuilder.addInt16(1, damage);
return fbBuilder.offset;
@@ -395,17 +415,15 @@ class WeaponObjectBuilder extends fb.ObjectBuilder {
final String? _name;
final int? _damage;
WeaponObjectBuilder({
String? name,
int? damage,
})
: _name = name,
_damage = damage;
WeaponObjectBuilder({String? name, int? damage})
: _name = name,
_damage = damage;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? nameOffset = _name == null ? null
final int? nameOffset = _name == null
? null
: fbBuilder.writeString(_name!);
fbBuilder.startTable(2);
fbBuilder.addOffset(0, nameOffset);

View File

@@ -27,10 +27,11 @@ class BufferContext {
ByteData get buffer => _buffer;
/// Create from a FlatBuffer represented by a list of bytes (uint8).
factory BufferContext.fromBytes(List<int> byteList) =>
BufferContext(byteList is Uint8List
? byteList.buffer.asByteData(byteList.offsetInBytes)
: ByteData.view(Uint8List.fromList(byteList).buffer));
factory BufferContext.fromBytes(List<int> byteList) => BufferContext(
byteList is Uint8List
? byteList.buffer.asByteData(byteList.offsetInBytes)
: ByteData.view(Uint8List.fromList(byteList).buffer),
);
/// Create from a FlatBuffer represented by ByteData.
BufferContext(this._buffer);
@@ -149,9 +150,9 @@ class Builder {
bool internStrings = false,
Allocator allocator = const DefaultAllocator(),
this.deduplicateTables = true,
}) : _allocator = allocator,
_buf = allocator.allocate(initialSize),
_vTables = deduplicateTables ? [] : const [] {
}) : _allocator = allocator,
_buf = allocator.allocate(initialSize),
_vTables = deduplicateTables ? [] : const [] {
if (internStrings) {
_strings = <String, int>{};
}
@@ -350,8 +351,10 @@ class Builder {
Uint8List get buffer {
assert(_finished);
final finishedSize = size();
return _buf.buffer
.asUint8List(_buf.lengthInBytes - finishedSize, finishedSize);
return _buf.buffer.asUint8List(
_buf.lengthInBytes - finishedSize,
finishedSize,
);
}
/// Finish off the creation of the buffer. The given [offset] is used as the
@@ -368,14 +371,18 @@ class Builder {
if (fileIdentifier != null) {
for (var i = 0; i < 4; i++) {
_setUint8AtTail(
finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i));
finishedSize - _sizeofUint32 - i,
fileIdentifier.codeUnitAt(i),
);
}
}
// zero out the added padding
for (var i = sizeBeforePadding + 1;
i <= finishedSize - requiredBytes;
i++) {
for (
var i = sizeBeforePadding + 1;
i <= finishedSize - requiredBytes;
i++
) {
_setUint8AtTail(i, 0);
}
_finished = true;
@@ -687,8 +694,10 @@ class Builder {
int writeString(String value, {bool asciiOptimization = false}) {
assert(!_inVTable);
if (_strings != null) {
return _strings!
.putIfAbsent(value, () => _writeString(value, asciiOptimization));
return _strings!.putIfAbsent(
value,
() => _writeString(value, asciiOptimization),
);
} else {
return _writeString(value, asciiOptimization);
}
@@ -1005,8 +1014,11 @@ class ListReader<E> extends Reader<List<E>> {
: List<E>.generate(
bc.buffer.getUint32(listOffset, Endian.little),
(int index) => _elementReader.read(
bc, listOffset + size + _elementReader.size * index),
growable: true);
bc,
listOffset + size + _elementReader.size * index,
),
growable: true,
);
}
}
@@ -1284,7 +1296,7 @@ class _FbGenericList<E> extends _FbList<E> {
List<E?>? _items;
_FbGenericList(this.elementReader, BufferContext bp, int offset)
: super(bp, offset);
: super(bp, offset);
@override
@pragma('vm:prefer-inline')
@@ -1454,7 +1466,11 @@ abstract class Allocator {
/// Params [inUseBack] and [inUseFront] indicate how much of [oldData] is
/// actually in use at each end, and needs to be copied.
ByteData resize(
ByteData oldData, int newSize, int inUseBack, int inUseFront) {
ByteData oldData,
int newSize,
int inUseBack,
int inUseFront,
) {
final newData = allocate(newSize);
_copyDownward(oldData, newData, inUseBack, inUseFront);
deallocate(oldData);
@@ -1465,17 +1481,25 @@ abstract class Allocator {
/// memory of size [inUseFront] and [inUseBack] will be copied from the front
/// and back of the old memory allocation.
void _copyDownward(
ByteData oldData, ByteData newData, int inUseBack, int inUseFront) {
ByteData oldData,
ByteData newData,
int inUseBack,
int inUseFront,
) {
if (inUseBack != 0) {
newData.buffer.asUint8List().setAll(
newData.lengthInBytes - inUseBack,
oldData.buffer.asUint8List().getRange(
oldData.lengthInBytes - inUseBack, oldData.lengthInBytes));
newData.lengthInBytes - inUseBack,
oldData.buffer.asUint8List().getRange(
oldData.lengthInBytes - inUseBack,
oldData.lengthInBytes,
),
);
}
if (inUseFront != 0) {
newData.buffer
.asUint8List()
.setAll(0, oldData.buffer.asUint8List().getRange(0, inUseFront));
newData.buffer.asUint8List().setAll(
0,
oldData.buffer.asUint8List().getRange(0, inUseFront),
);
}
}
}

View File

@@ -107,8 +107,11 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue =
_StackValue.withOffset(stringOffset, ValueType.String, bitWidth);
final stackValue = _StackValue.withOffset(
stringOffset,
ValueType.String,
bitWidth,
);
_stack.add(stackValue);
_stringCache[value] = stackValue;
}
@@ -128,8 +131,11 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue =
_StackValue.withOffset(keyOffset, ValueType.Key, BitWidth.width8);
final stackValue = _StackValue.withOffset(
keyOffset,
ValueType.Key,
BitWidth.width8,
);
_stack.add(stackValue);
_keyCache[value] = stackValue;
}
@@ -147,8 +153,11 @@ class Builder {
final newOffset = _newOffset(length);
_pushBuffer(value.asUint8List());
_offset = newOffset;
final stackValue =
_StackValue.withOffset(blobOffset, ValueType.Blob, bitWidth);
final stackValue = _StackValue.withOffset(
blobOffset,
ValueType.Blob,
bitWidth,
);
_stack.add(stackValue);
}
@@ -170,7 +179,10 @@ class Builder {
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.withOffset(
valueOffset, ValueType.IndirectInt, stackValue.width);
valueOffset,
ValueType.IndirectInt,
stackValue.width,
);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -195,7 +207,10 @@ class Builder {
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.withOffset(
valueOffset, ValueType.IndirectFloat, stackValue.width);
valueOffset,
ValueType.IndirectFloat,
stackValue.width,
);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -252,9 +267,10 @@ class Builder {
tmp._offset = _offset;
tmp._stack = List.from(_stack);
tmp._stackPointers = List.from(_stackPointers);
tmp._buffer.buffer
.asUint8List()
.setAll(0, _buffer.buffer.asUint8List(0, _offset));
tmp._buffer.buffer.asUint8List().setAll(
0,
_buffer.buffer.asUint8List(0, _offset),
);
for (var i = 0; i < tmp._stackPointers.length; i++) {
tmp.end();
}
@@ -271,7 +287,8 @@ class Builder {
if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) {
if (_stack.last.type != ValueType.Key) {
throw StateError(
'Adding value to a map before adding a key is prohibited');
'Adding value to a map before adding a key is prohibited',
);
}
}
}
@@ -288,7 +305,8 @@ class Builder {
void _finish() {
if (_stack.length != 1) {
throw StateError(
'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]',
);
}
final value = _stack[0];
final byteWidth = _align(value.elementWidth(_offset, 0));
@@ -298,8 +316,12 @@ class Builder {
_finished = true;
}
_StackValue _createVector(int start, int vecLength, int step,
[_StackValue? keys]) {
_StackValue _createVector(
int start,
int vecLength,
int step, [
_StackValue? keys,
]) {
var bitWidth = BitWidthUtil.uwidth(vecLength);
var prefixElements = 1;
if (keys != null) {
@@ -326,7 +348,8 @@ class Builder {
}
}
final byteWidth = _align(bitWidth);
final fix = typed & ValueTypeUtils.isNumber(vectorType) &&
final fix =
typed & ValueTypeUtils.isNumber(vectorType) &&
vecLength >= 2 &&
vecLength <= 4;
if (keys != null) {
@@ -349,8 +372,10 @@ class Builder {
return _StackValue.withOffset(vecOffset, ValueType.Map, bitWidth);
}
if (typed) {
final vType =
ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
final vType = ValueTypeUtils.toTypedVector(
vectorType,
fix ? vecLength : 0,
);
return _StackValue.withOffset(vecOffset, vType, bitWidth);
}
return _StackValue.withOffset(vecOffset, ValueType.Vector, bitWidth);
@@ -366,7 +391,8 @@ class Builder {
void _sortKeysAndEndMap(_StackPointer pointer) {
if (((_stack.length - pointer.stackPosition) & 1) == 1) {
throw StateError(
'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.',
);
}
var sorted = true;
@@ -412,8 +438,12 @@ class Builder {
keysStackValue = _createVector(pointer.stackPosition, vecLength, 2);
_keyVectorCache[keysHash] = keysStackValue;
}
final vec =
_createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
final vec = _createVector(
pointer.stackPosition + 1,
vecLength,
2,
keysStackValue,
);
_stack.removeRange(pointer.stackPosition, _stack.length);
_stack.add(vec);
}
@@ -421,7 +451,8 @@ class Builder {
bool _shouldFlip(_StackValue v1, _StackValue v2) {
if (v1.type != ValueType.Key || v2.type != ValueType.Key) {
throw StateError(
'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.',
);
}
late int c1, c2;
@@ -450,7 +481,8 @@ class Builder {
_writeUInt(relativeOffset, byteWidth);
} else {
throw StateError(
'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
} else {
_pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth)));
@@ -523,29 +555,27 @@ class _StackValue {
final ValueType _type;
final BitWidth _width;
_StackValue.withNull()
: _type = ValueType.Null,
_width = BitWidth.width8;
_StackValue.withNull() : _type = ValueType.Null, _width = BitWidth.width8;
_StackValue.withInt(int value)
: _type = ValueType.Int,
_width = BitWidthUtil.width(value),
_value = value;
: _type = ValueType.Int,
_width = BitWidthUtil.width(value),
_value = value;
_StackValue.withBool(bool value)
: _type = ValueType.Bool,
_width = BitWidth.width8,
_value = value;
: _type = ValueType.Bool,
_width = BitWidth.width8,
_value = value;
_StackValue.withDouble(double value)
: _type = ValueType.Float,
_width = BitWidthUtil.width(value),
_value = value;
: _type = ValueType.Float,
_width = BitWidthUtil.width(value),
_value = value;
_StackValue.withOffset(int value, ValueType type, BitWidth width)
: _offset = value,
_type = type,
_width = width;
: _offset = value,
_type = type,
_width = width;
BitWidth storedWidth({BitWidth width = BitWidth.width8}) {
return ValueTypeUtils.isInline(_type)
@@ -562,16 +592,16 @@ class _StackValue {
final offset = _offset!;
for (var i = 0; i < 4; i++) {
final width = 1 << i;
final bitWidth = BitWidthUtil.uwidth(size +
BitWidthUtil.paddingSize(size, width) +
index * width -
offset);
final bitWidth = BitWidthUtil.uwidth(
size + BitWidthUtil.paddingSize(size, width) + index * width - offset,
);
if (1 << bitWidth.index == width) {
return bitWidth;
}
}
throw StateError(
'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
List<int> asU8List(BitWidth width) {
@@ -619,7 +649,8 @@ class _StackValue {
}
throw StateError(
'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new',
);
}
ValueType get type {

View File

@@ -1,6 +1,7 @@
import 'dart:collection';
import 'dart:convert';
import 'dart:typed_data';
import 'types.dart';
/// Main class to read a value out of a FlexBuffer.
@@ -16,10 +17,15 @@ class Reference {
int? _length;
Reference._(
this._buffer, this._offset, this._parentWidth, int packedType, this._path,
[int? byteWidth, ValueType? valueType])
: _byteWidth = byteWidth ?? 1 << (packedType & 3),
_valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2);
this._buffer,
this._offset,
this._parentWidth,
int packedType,
this._path, [
int? byteWidth,
ValueType? valueType,
]) : _byteWidth = byteWidth ?? 1 << (packedType & 3),
_valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2);
/// Use this method to access the root value of a FlexBuffer.
static Reference fromBuffer(ByteBuffer buffer) {
@@ -31,8 +37,13 @@ class Reference {
final byteWidth = byteData.getUint8(len - 1);
final packedType = byteData.getUint8(len - 2);
final offset = len - byteWidth - 2;
return Reference._(ByteData.view(buffer), offset,
BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
return Reference._(
ByteData.view(buffer),
offset,
BitWidthUtil.fromByteWidth(byteWidth),
packedType,
"/",
);
}
/// Returns true if the underlying value is null.
@@ -138,7 +149,8 @@ class Reference {
final index = key;
if (index >= length || index < 0) {
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
'Key: [$key] is not applicable on: $_path of: $_valueType length: $length',
);
}
final elementOffset = _indirect + index * _byteWidth;
int packedType = 0;
@@ -154,13 +166,14 @@ class Reference {
packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
}
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path[$index]",
byteWidth,
valueType);
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path[$index]",
byteWidth,
valueType,
);
}
if (key is String && _valueType == ValueType.Map) {
final index = _keyIndex(key);
@@ -169,7 +182,8 @@ class Reference {
}
}
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType');
'Key: [$key] is not applicable on: $_path of: $_valueType',
);
}
/// Get an iterable if the underlying flexBuffer value is a vector.
@@ -213,18 +227,24 @@ class Reference {
ValueTypeUtils.isAVector(_valueType) ||
_valueType == ValueType.Map) {
_length = _readUInt(
_indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
_indirect - _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
} else if (_valueType == ValueType.Null) {
_length = 0;
} else if (_valueType == ValueType.String) {
final indirect = _indirect;
var sizeByteWidth = _byteWidth;
var size = _readUInt(indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth));
var size = _readUInt(
indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth),
);
while (_buffer.getInt8(indirect + size) != 0) {
sizeByteWidth <<= 1;
size = _readUInt(indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth));
size = _readUInt(
indirect - sizeByteWidth,
BitWidthUtil.fromByteWidth(sizeByteWidth),
);
}
_length = size;
} else if (_valueType == ValueType.Key) {
@@ -289,7 +309,8 @@ class Reference {
return result.toString();
}
throw UnsupportedError(
'Type: $_valueType is not supported for JSON conversion');
'Type: $_valueType is not supported for JSON conversion',
);
}
/// Computes the indirect offset of the value.
@@ -354,10 +375,13 @@ class Reference {
int? _keyIndex(String key) {
final input = utf8.encode(key);
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset -
final indirectOffset =
keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
keysVectorOffset + _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
var low = 0;
var high = length - 1;
while (low <= high) {
@@ -390,24 +414,37 @@ class Reference {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path/$key",
);
}
Reference _valueForIndex(int index) {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path/[$index]",
);
}
String _keyForIndex(int index) {
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset -
final indirectOffset =
keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
keysVectorOffset + _byteWidth,
BitWidthUtil.fromByteWidth(_byteWidth),
);
final keyOffset = indirectOffset + index * byteWidth;
final keyIndirectOffset =
keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));

View File

@@ -86,7 +86,8 @@ enum ValueType {
VectorFloat,
VectorKey,
@Deprecated(
'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)',
)
VectorString,
VectorInt2,
VectorUInt2,
@@ -99,7 +100,7 @@ enum ValueType {
VectorFloat4,
Blob,
Bool,
VectorBool
VectorBool,
}
class ValueTypeUtils {
@@ -153,31 +154,37 @@ class ValueTypeUtils {
static ValueType toTypedVector(ValueType self, int length) {
if (length == 0) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt),
);
}
if (length == 2) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2),
);
}
if (length == 3) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3),
);
}
if (length == 4) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4),
);
}
throw Exception('unexpected length ' + length.toString());
}
static ValueType typedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int),
);
}
static ValueType fixedTypedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt(
(toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
(toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int),
);
}
static int fixedTypedVectorElementSize(ValueType self) {

View File

@@ -2,8 +2,8 @@
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:flat_buffers/flat_buffers.dart' as fb;
class Foo {
Foo._(this._bc, this._bcOffset);
@@ -17,15 +17,15 @@ class Foo {
final fb.BufferContext _bc;
final int _bcOffset;
FooProperties? get myFoo => FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4);
FooProperties? get myFoo =>
FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'Foo{myFoo: ${myFoo}}';
}
FooT unpack() => FooT(
myFoo: myFoo?.unpack());
FooT unpack() => FooT(myFoo: myFoo?.unpack());
static int pack(fb.Builder fbBuilder, FooT? object) {
if (object == null) return 0;
@@ -36,8 +36,7 @@ class Foo {
class FooT implements fb.Packable {
FooPropertiesT? myFoo;
FooT({
this.myFoo});
FooT({this.myFoo});
@override
int pack(fb.Builder fbBuilder) {
@@ -58,8 +57,7 @@ class _FooReader extends fb.TableReader<Foo> {
const _FooReader();
@override
Foo createObject(fb.BufferContext bc, int offset) =>
Foo._(bc, offset);
Foo createObject(fb.BufferContext bc, int offset) => Foo._(bc, offset);
}
class FooBuilder {
@@ -84,10 +82,7 @@ class FooBuilder {
class FooObjectBuilder extends fb.ObjectBuilder {
final FooPropertiesObjectBuilder? _myFoo;
FooObjectBuilder({
FooPropertiesObjectBuilder? myFoo,
})
: _myFoo = myFoo;
FooObjectBuilder({FooPropertiesObjectBuilder? myFoo}) : _myFoo = myFoo;
/// Finish building, and store into the [fbBuilder].
@override
@@ -107,6 +102,7 @@ class FooObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class FooProperties {
FooProperties._(this._bc, this._bcOffset);
@@ -123,9 +119,7 @@ class FooProperties {
return 'FooProperties{a: ${a}, b: ${b}}';
}
FooPropertiesT unpack() => FooPropertiesT(
a: a,
b: b);
FooPropertiesT unpack() => FooPropertiesT(a: a, b: b);
static int pack(fb.Builder fbBuilder, FooPropertiesT? object) {
if (object == null) return 0;
@@ -137,9 +131,7 @@ class FooPropertiesT implements fb.Packable {
bool a;
bool b;
FooPropertiesT({
required this.a,
required this.b});
FooPropertiesT({required this.a, required this.b});
@override
int pack(fb.Builder fbBuilder) {
@@ -161,8 +153,8 @@ class _FooPropertiesReader extends fb.StructReader<FooProperties> {
int get size => 2;
@override
FooProperties createObject(fb.BufferContext bc, int offset) =>
FooProperties._(bc, offset);
FooProperties createObject(fb.BufferContext bc, int offset) =>
FooProperties._(bc, offset);
}
class FooPropertiesBuilder {
@@ -175,19 +167,15 @@ class FooPropertiesBuilder {
fbBuilder.putBool(a);
return fbBuilder.offset;
}
}
class FooPropertiesObjectBuilder extends fb.ObjectBuilder {
final bool _a;
final bool _b;
FooPropertiesObjectBuilder({
required bool a,
required bool b,
})
: _a = a,
_b = b;
FooPropertiesObjectBuilder({required bool a, required bool b})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override

View File

@@ -2,8 +2,8 @@
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:flat_buffers/flat_buffers.dart' as fb;
enum OptionsEnum {
A(1),
@@ -15,10 +15,14 @@ enum OptionsEnum {
factory OptionsEnum.fromValue(int value) {
switch (value) {
case 1: return OptionsEnum.A;
case 2: return OptionsEnum.B;
case 3: return OptionsEnum.C;
default: throw StateError('Invalid value $value for bit flag enum');
case 1:
return OptionsEnum.A;
case 2:
return OptionsEnum.B;
case 3:
return OptionsEnum.C;
default:
throw StateError('Invalid value $value for bit flag enum');
}
}
@@ -53,7 +57,9 @@ class MyTable {
final fb.BufferContext _bc;
final int _bcOffset;
List<OptionsEnum>? get options => const fb.ListReader<OptionsEnum>(OptionsEnum.reader).vTableGetNullable(_bc, _bcOffset, 4);
List<OptionsEnum>? get options => const fb.ListReader<OptionsEnum>(
OptionsEnum.reader,
).vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
@@ -61,7 +67,11 @@ class MyTable {
}
MyTableT unpack() => MyTableT(
options: const fb.ListReader<OptionsEnum>(OptionsEnum.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 4));
options: const fb.ListReader<OptionsEnum>(
OptionsEnum.reader,
lazy: false,
).vTableGetNullable(_bc, _bcOffset, 4),
);
static int pack(fb.Builder fbBuilder, MyTableT? object) {
if (object == null) return 0;
@@ -72,12 +82,12 @@ class MyTable {
class MyTableT implements fb.Packable {
List<OptionsEnum>? options;
MyTableT({
this.options});
MyTableT({this.options});
@override
int pack(fb.Builder fbBuilder) {
final int? optionsOffset = options == null ? null
final int? optionsOffset = options == null
? null
: fbBuilder.writeListUint32(options!.map((f) => f.value).toList());
fbBuilder.startTable(1);
fbBuilder.addOffset(0, optionsOffset);
@@ -94,8 +104,8 @@ class _MyTableReader extends fb.TableReader<MyTable> {
const _MyTableReader();
@override
MyTable createObject(fb.BufferContext bc, int offset) =>
MyTable._(bc, offset);
MyTable createObject(fb.BufferContext bc, int offset) =>
MyTable._(bc, offset);
}
class MyTableBuilder {
@@ -120,15 +130,13 @@ class MyTableBuilder {
class MyTableObjectBuilder extends fb.ObjectBuilder {
final List<OptionsEnum>? _options;
MyTableObjectBuilder({
List<OptionsEnum>? options,
})
: _options = options;
MyTableObjectBuilder({List<OptionsEnum>? options}) : _options = options;
/// Finish building, and store into the [fbBuilder].
@override
int finish(fb.Builder fbBuilder) {
final int? optionsOffset = _options == null ? null
final int? optionsOffset = _options == null
? null
: fbBuilder.writeListUint32(_options!.map((f) => f.value).toList());
fbBuilder.startTable(1);
fbBuilder.addOffset(0, optionsOffset);

View File

@@ -1,16 +1,15 @@
import 'dart:typed_data';
import 'dart:io' as io;
import 'package:path/path.dart' as path;
import 'dart:typed_data';
import 'package:flat_buffers/flat_buffers.dart';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import './monster_test_my_game.example_generated.dart' as example;
import './monster_test_my_game.example2_generated.dart' as example2;
import 'enums_generated.dart' as example3;
import './bool_structs_generated.dart' as example4;
import './monster_test_my_game.example2_generated.dart' as example2;
import './monster_test_my_game.example_generated.dart' as example;
import 'enums_generated.dart' as example3;
main() {
defineReflectiveSuite(() {
@@ -29,11 +28,9 @@ int indexToField(int index) {
@reflectiveTest
class CheckOtherLangaugesData {
test_cppData() async {
List<int> data = await io.File(path.join(
path.context.current,
'test',
'monsterdata_test.mon',
)).readAsBytes();
List<int> data = await io.File(
path.join(path.context.current, 'test', 'monsterdata_test.mon'),
).readAsBytes();
example.Monster mon = example.Monster(data);
expect(mon.hp, 80);
expect(mon.mana, 150);
@@ -61,91 +58,92 @@ class CheckOtherLangaugesData {
// this will fail if accessing any field fails.
expect(
mon.toString(),
'Monster{'
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, '
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color.Blue, testType: AnyTypeId.Monster, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, '
'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, '
'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, '
'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, '
'testarrayofsortedstruct: null, flex: null, test5: null, '
'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, '
'vectorOfReferrables: null, singleWeakReference: 0, '
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, '
'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, '
'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, '
'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, '
'testarrayofsortedstruct: null, flex: null, test5: null, '
'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, '
'vectorOfReferrables: null, singleWeakReference: 0, '
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'testnestedflatbuffer: null, testempty: null, testbool: true, '
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
'testhashs64Fnv1: 7930699090847568257, '
'testhashu64Fnv1: 7930699090847568257, '
'testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, '
'testhashs64Fnv1a: 4898026182817603057, '
'testhashu64Fnv1a: 4898026182817603057, '
'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, '
'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: ['
'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, '
'Ability{id: 5, distance: 12}], '
'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], '
'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], '
'parentNamespaceTest: null, vectorOfReferrables: null, '
'singleWeakReference: 0, vectorOfWeakReferences: null, '
'vectorOfStrongReferrables: null, coOwningReference: 0, '
'vectorOfCoOwningReferences: null, nonOwningReference: 0, '
'vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, '
'anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
'nativeInline: Test{a: 1, b: 2}, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}');
mon.toString(),
'Monster{'
'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, '
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color.Blue, testType: AnyTypeId.Monster, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, '
'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, '
'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, '
'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, '
'testarrayofsortedstruct: null, flex: null, test5: null, '
'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, '
'vectorOfReferrables: null, singleWeakReference: 0, '
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color.Blue, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, '
'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, '
'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, '
'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, '
'testarrayofsortedstruct: null, flex: null, test5: null, '
'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, '
'vectorOfReferrables: null, singleWeakReference: 0, '
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, '
'nativeInline: null, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, '
'testnestedflatbuffer: null, testempty: null, testbool: true, '
'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, '
'testhashs64Fnv1: 7930699090847568257, '
'testhashu64Fnv1: 7930699090847568257, '
'testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, '
'testhashs64Fnv1a: 4898026182817603057, '
'testhashu64Fnv1a: 4898026182817603057, '
'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, '
'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: ['
'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, '
'Ability{id: 5, distance: 12}], '
'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], '
'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], '
'parentNamespaceTest: null, vectorOfReferrables: null, '
'singleWeakReference: 0, vectorOfWeakReferences: null, '
'vectorOfStrongReferrables: null, coOwningReference: 0, '
'vectorOfCoOwningReferences: null, nonOwningReference: 0, '
'vectorOfNonOwningReferences: null, '
'anyUniqueType: null, anyUnique: null, '
'anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], '
'nativeInline: Test{a: 1, b: 2}, '
'longEnumNonEnumDefault: LongEnum._default, '
'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, '
'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: '
'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: '
'-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}',
);
}
}
@@ -298,20 +296,72 @@ class BuilderTest {
expect(allocator.buffer(builder.size()), [2, 0, 0, 0, 0, 0, 0, 1]);
builder.putUint8(3);
expect(
allocator.buffer(builder.size()), [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
0,
0,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint8(4);
expect(
allocator.buffer(builder.size()), [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
0,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint8(5);
expect(
allocator.buffer(builder.size()), [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
0,
5,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
builder.putUint32(6);
expect(allocator.buffer(builder.size()),
[6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]);
expect(allocator.buffer(builder.size()), [
6,
0,
0,
0,
0,
5,
4,
3,
2,
0,
0,
0,
0,
0,
0,
1,
]);
}
void test_table_default() {
@@ -331,14 +381,14 @@ class BuilderTest {
int objectOffset = buffer.derefObject(0);
// was not written, so uses the new default value
expect(
const Int32Reader()
.vTableGet(buffer, objectOffset, indexToField(0), 15),
15);
const Int32Reader().vTableGet(buffer, objectOffset, indexToField(0), 15),
15,
);
// has the written value
expect(
const Int32Reader()
.vTableGet(buffer, objectOffset, indexToField(1), 15),
20);
const Int32Reader().vTableGet(buffer, objectOffset, indexToField(1), 15),
20,
);
}
void test_table_format([Builder? builder]) {
@@ -370,7 +420,9 @@ class BuilderTest {
for (int i = 0; i < 3; i++) {
int offset = byteData.getUint16(vTableLoc + 4 + 2 * i, Endian.little);
expect(
byteData.getInt32(tableDataLoc + offset, Endian.little), 10 + 10 * i);
byteData.getInt32(tableDataLoc + offset, Endian.little),
10 + 10 * i,
);
}
}
@@ -380,10 +432,14 @@ class BuilderTest {
List<int> byteList;
{
Builder builder = Builder(initialSize: 0);
int? latinStringOffset =
builder.writeString(latinString, asciiOptimization: true);
int? unicodeStringOffset =
builder.writeString(unicodeString, asciiOptimization: true);
int? latinStringOffset = builder.writeString(
latinString,
asciiOptimization: true,
);
int? unicodeStringOffset = builder.writeString(
unicodeString,
asciiOptimization: true,
);
builder.startTable(2);
builder.addOffset(0, latinStringOffset);
builder.addOffset(1, unicodeStringOffset);
@@ -395,13 +451,19 @@ class BuilderTest {
BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
latinString);
const StringReader().vTableGetNullable(
buf,
objectOffset,
indexToField(0),
),
latinString,
);
expect(
const StringReader(asciiOptimization: true)
.vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString);
const StringReader(
asciiOptimization: true,
).vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString,
);
}
void test_table_types([Builder? builder]) {
@@ -425,33 +487,41 @@ class BuilderTest {
BufferContext buf = BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
const BoolReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
true);
const BoolReader().vTableGetNullable(buf, objectOffset, indexToField(0)),
true,
);
expect(
const Int8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(1)),
10);
const Int8Reader().vTableGetNullable(buf, objectOffset, indexToField(1)),
10,
);
expect(
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(2)),
20);
const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(2)),
20,
);
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(3)),
'12345');
const StringReader().vTableGetNullable(
buf,
objectOffset,
indexToField(3),
),
'12345',
);
expect(
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(4)),
40);
const Int32Reader().vTableGetNullable(buf, objectOffset, indexToField(4)),
40,
);
expect(
const Uint32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(5)),
0x9ABCDEF0);
const Uint32Reader().vTableGetNullable(
buf,
objectOffset,
indexToField(5),
),
0x9ABCDEF0,
);
expect(
const Uint8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A);
const Uint8Reader().vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A,
);
}
void test_writeList_of_Uint32() {
@@ -596,8 +666,9 @@ class BuilderTest {
}
// read and verify
BufferContext buf = BufferContext.fromBytes(byteList);
List<TestPointImpl> items =
const ListReader<TestPointImpl>(TestPointReader()).read(buf, 0);
List<TestPointImpl> items = const ListReader<TestPointImpl>(
TestPointReader(),
).read(buf, 0);
expect(items, hasLength(2));
expect(items[0].x, 10);
expect(items[0].y, 20);
@@ -627,8 +698,10 @@ class BuilderTest {
List<int> byteList;
{
builder ??= Builder(initialSize: 0);
int listOffset = builder.writeList(
[builder.writeString('12345'), builder.writeString('ABC')]);
int listOffset = builder.writeList([
builder.writeString('12345'),
builder.writeString('ABC'),
]);
builder.startTable(1);
builder.addOffset(0, listOffset);
int offset = builder.endTable();
@@ -707,13 +780,14 @@ class BuilderTest {
test_table_format,
test_table_types,
test_writeList_ofObjects,
test_writeList_ofStrings_inObject
test_writeList_ofStrings_inObject,
];
// Execute all test cases in all permutations of their order.
// To do that, we generate permutations of test case indexes.
final testCasesPermutations =
_permutationsOf(List.generate(testCases.length, (index) => index));
final testCasesPermutations = _permutationsOf(
List.generate(testCases.length, (index) => index),
);
expect(testCasesPermutations.length, _factorial(testCases.length));
for (var indexes in testCasesPermutations) {
@@ -783,12 +857,13 @@ class ObjectAPITest {
void test_tableMonster() {
final monster = example.MonsterT()
..pos = example.Vec3T(
x: 1,
y: 2,
z: 3,
test1: 4.0,
test2: example.Color.Red,
test3: example.TestT(a: 1, b: 2))
x: 1,
y: 2,
z: 3,
test1: 4.0,
test2: example.Color.Red,
test3: example.TestT(a: 1, b: 2),
)
..mana = 2
..name = 'Monstrous'
..inventory = [24, 42]
@@ -804,7 +879,7 @@ class ObjectAPITest {
..testf = 42.24
..testarrayofsortedstruct = [
example.AbilityT(id: 1, distance: 5),
example.AbilityT(id: 3, distance: 7)
example.AbilityT(id: 3, distance: 7),
]
..vectorOfLongs = [5, 6, 7]
..vectorOfDoubles = [8.9, 9.0, 10.1, 11.2]
@@ -867,8 +942,9 @@ class StringListWrapperImpl {
StringListWrapperImpl(this.bp, this.offset);
List<String>? get items => const ListReader<String>(StringReader())
.vTableGetNullable(bp, offset, indexToField(0));
List<String>? get items => const ListReader<String>(
StringReader(),
).vTableGetNullable(bp, offset, indexToField(0));
}
class StringListWrapperReader extends TableReader<StringListWrapperImpl> {
@@ -906,10 +982,14 @@ class GeneratorTest {
expect(example.Color.values, same(example.Color.values));
expect(example.Race.values, same(example.Race.values));
expect(example.AnyTypeId.values, same(example.AnyTypeId.values));
expect(example.AnyUniqueAliasesTypeId.values,
same(example.AnyUniqueAliasesTypeId.values));
expect(example.AnyAmbiguousAliasesTypeId.values,
same(example.AnyAmbiguousAliasesTypeId.values));
expect(
example.AnyUniqueAliasesTypeId.values,
same(example.AnyUniqueAliasesTypeId.values),
);
expect(
example.AnyAmbiguousAliasesTypeId.values,
same(example.AnyAmbiguousAliasesTypeId.values),
);
}
}
@@ -917,11 +997,13 @@ class GeneratorTest {
@reflectiveTest
class ListOfEnumsTest {
void test_listOfEnums() async {
var mytable = example3.MyTableObjectBuilder(options: [
example3.OptionsEnum.A,
example3.OptionsEnum.B,
example3.OptionsEnum.C
]);
var mytable = example3.MyTableObjectBuilder(
options: [
example3.OptionsEnum.A,
example3.OptionsEnum.B,
example3.OptionsEnum.C,
],
);
var bytes = mytable.toBytes();
var mytable_read = example3.MyTable(bytes);
expect(mytable_read.options![0].value, example3.OptionsEnum.A.value);
@@ -934,7 +1016,8 @@ class ListOfEnumsTest {
class BoolInStructTest {
void test_boolInStruct() async {
var mystruct = example4.FooObjectBuilder(
myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false));
myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false),
);
var bytes = mystruct.toBytes();
var mystruct_read = example4.Foo(bytes);
expect(mystruct_read.myFoo!.a, true);

View File

@@ -62,8 +62,23 @@ void main() {
{
var flx = Builder();
flx.addString('hello 😱');
expect(flx.finish(),
[10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
expect(flx.finish(), [
10,
104,
101,
108,
108,
111,
32,
240,
159,
152,
177,
0,
11,
20,
1,
]);
}
});
@@ -117,7 +132,7 @@ void main() {
192,
16,
75,
1
1,
]);
}
{
@@ -177,7 +192,7 @@ void main() {
7,
3,
60,
1
1,
]);
}
{
@@ -215,7 +230,7 @@ void main() {
10,
6,
60,
1
1,
]);
}
{
@@ -300,7 +315,7 @@ void main() {
104,
45,
43,
1
1,
]);
}
});
@@ -322,8 +337,24 @@ void main() {
..addKey('')
..addInt(45)
..end();
expect(
flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
expect(flx.finish(), [
97,
0,
0,
2,
2,
5,
2,
1,
2,
45,
12,
4,
4,
4,
36,
1,
]);
}
{
var flx = Builder()
@@ -367,7 +398,7 @@ void main() {
36,
4,
40,
1
1,
]);
}
});
@@ -381,133 +412,152 @@ void main() {
test('build from object', () {
expect(
Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer)
.asUint8List(),
[3, 1, 2, 3, 3, 100, 1]);
Builder.buildFromObject(
Uint8List.fromList([1, 2, 3]).buffer,
).asUint8List(),
[3, 1, 2, 3, 3, 100, 1],
);
expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]);
expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]);
expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]);
expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]);
expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]);
expect(Builder.buildFromObject(-2.50).asUint8List(), [
0,
0,
32,
192,
14,
4,
]);
expect(Builder.buildFromObject('Maxim').asUint8List(), [
5,
77,
97,
120,
105,
109,
0,
6,
20,
1,
]);
expect(
Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
expect(Builder.buildFromObject('Maxim').asUint8List(),
[5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(),
[
3,
109,
97,
120,
0,
0,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
102,
102,
102,
102,
102,
102,
10,
64,
31,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
15,
20,
104,
0,
104,
54,
43,
1,
],
);
expect(
Builder.buildFromObject([1, 3.3, 'max', true, null, false])
.asUint8List(),
[
3,
109,
97,
120,
0,
0,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
102,
102,
102,
102,
102,
102,
10,
64,
31,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
15,
20,
104,
0,
104,
54,
43,
1
]);
expect(
Builder.buildFromObject([
{'something': 12},
{'something': 45}
]).asUint8List(),
[
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1
]);
Builder.buildFromObject([
{'something': 12},
{'something': 45},
]).asUint8List(),
[
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1,
],
);
});
test('add double indirectly', () {
@@ -543,7 +593,7 @@ void main() {
35,
8,
40,
1
1,
]);
});
@@ -580,7 +630,7 @@ void main() {
27,
8,
40,
1
1,
]);
});

File diff suppressed because it is too large Load Diff

View File

@@ -48,116 +48,210 @@ void main() {
expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse);
});
test('to typed vector', () {
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0),
equals(ValueType.VectorInt));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
equals(ValueType.VectorUInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
equals(ValueType.VectorBool));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0),
equals(ValueType.VectorFloat));
expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0),
equals(ValueType.VectorKey));
expect(ValueTypeUtils.toTypedVector(ValueType.String, 0),
equals(ValueType.VectorString));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 0),
equals(ValueType.VectorInt),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
equals(ValueType.VectorUInt),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
equals(ValueType.VectorBool),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 0),
equals(ValueType.VectorFloat),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Key, 0),
equals(ValueType.VectorKey),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.String, 0),
equals(ValueType.VectorString),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2),
equals(ValueType.VectorInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
equals(ValueType.VectorUInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2),
equals(ValueType.VectorFloat2));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 2),
equals(ValueType.VectorInt2),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
equals(ValueType.VectorUInt2),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 2),
equals(ValueType.VectorFloat2),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3),
equals(ValueType.VectorInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
equals(ValueType.VectorUInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3),
equals(ValueType.VectorFloat3));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 3),
equals(ValueType.VectorInt3),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
equals(ValueType.VectorUInt3),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 3),
equals(ValueType.VectorFloat3),
);
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4),
equals(ValueType.VectorInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4));
expect(
ValueTypeUtils.toTypedVector(ValueType.Int, 4),
equals(ValueType.VectorInt4),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4),
);
expect(
ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4),
);
});
test('typed vector element type', () {
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
equals(ValueType.Int));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
equals(ValueType.UInt));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
equals(ValueType.Float));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
equals(ValueType.String));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
equals(ValueType.Key));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
equals(ValueType.Bool));
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
equals(ValueType.String),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
equals(ValueType.Key),
);
expect(
ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
equals(ValueType.Bool),
);
});
test('fixed typed vector element type', () {
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
equals(ValueType.Int));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
equals(ValueType.Int),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
equals(ValueType.Int),
);
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
equals(ValueType.UInt));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
equals(ValueType.UInt),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
equals(ValueType.UInt),
);
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
equals(ValueType.Float));
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
equals(ValueType.Float),
);
expect(
ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
equals(ValueType.Float),
);
});
test('fixed typed vector element size', () {
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
equals(4),
);
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
equals(4),
);
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4));
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
equals(2),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3),
);
expect(
ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4),
);
});
test('packed type', () {
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8),
equals(0),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16),
equals(1),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32),
equals(2),
);
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64),
equals(3),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8),
equals(4),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16),
equals(5),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32),
equals(6),
);
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64),
equals(7),
);
});
test('bit width', () {
expect(BitWidthUtil.width(0), BitWidth.width8);

View File

@@ -2,10 +2,11 @@
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './include_test2_my_game.other_name_space_generated.dart' as my_game_other_name_space;
import './include_test2_my_game.other_name_space_generated.dart'
as my_game_other_name_space;
class TableA {
TableA._(this._bc, this._bcOffset);
@@ -19,15 +20,17 @@ class TableA {
final fb.BufferContext _bc;
final int _bcOffset;
my_game_other_name_space.TableB? get b => my_game_other_name_space.TableB.reader.vTableGetNullable(_bc, _bcOffset, 4);
my_game_other_name_space.TableB? get b => my_game_other_name_space
.TableB
.reader
.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
return 'TableA{b: ${b}}';
}
TableAT unpack() => TableAT(
b: b?.unpack());
TableAT unpack() => TableAT(b: b?.unpack());
static int pack(fb.Builder fbBuilder, TableAT? object) {
if (object == null) return 0;
@@ -38,8 +41,7 @@ class TableA {
class TableAT implements fb.Packable {
my_game_other_name_space.TableBT? b;
TableAT({
this.b});
TableAT({this.b});
@override
int pack(fb.Builder fbBuilder) {
@@ -59,8 +61,7 @@ class _TableAReader extends fb.TableReader<TableA> {
const _TableAReader();
@override
TableA createObject(fb.BufferContext bc, int offset) =>
TableA._(bc, offset);
TableA createObject(fb.BufferContext bc, int offset) => TableA._(bc, offset);
}
class TableABuilder {
@@ -85,10 +86,8 @@ class TableABuilder {
class TableAObjectBuilder extends fb.ObjectBuilder {
final my_game_other_name_space.TableBObjectBuilder? _b;
TableAObjectBuilder({
my_game_other_name_space.TableBObjectBuilder? b,
})
: _b = b;
TableAObjectBuilder({my_game_other_name_space.TableBObjectBuilder? b})
: _b = b;
/// Finish building, and store into the [fbBuilder].
@override

View File

@@ -4,8 +4,8 @@
library my_game.other_name_space;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './include_test1_generated.dart';
@@ -17,8 +17,10 @@ enum FromInclude {
factory FromInclude.fromValue(int value) {
switch (value) {
case 0: return FromInclude.IncludeVal;
default: throw StateError('Invalid value $value for bit flag enum');
case 0:
return FromInclude.IncludeVal;
default:
throw StateError('Invalid value $value for bit flag enum');
}
}
@@ -56,8 +58,7 @@ class Unused {
return 'Unused{a: ${a}}';
}
UnusedT unpack() => UnusedT(
a: a);
UnusedT unpack() => UnusedT(a: a);
static int pack(fb.Builder fbBuilder, UnusedT? object) {
if (object == null) return 0;
@@ -68,8 +69,7 @@ class Unused {
class UnusedT implements fb.Packable {
int a;
UnusedT({
required this.a});
UnusedT({required this.a});
@override
int pack(fb.Builder fbBuilder) {
@@ -90,8 +90,7 @@ class _UnusedReader extends fb.StructReader<Unused> {
int get size => 4;
@override
Unused createObject(fb.BufferContext bc, int offset) =>
Unused._(bc, offset);
Unused createObject(fb.BufferContext bc, int offset) => Unused._(bc, offset);
}
class UnusedBuilder {
@@ -103,16 +102,12 @@ class UnusedBuilder {
fbBuilder.putInt32(a);
return fbBuilder.offset;
}
}
class UnusedObjectBuilder extends fb.ObjectBuilder {
final int _a;
UnusedObjectBuilder({
required int a,
})
: _a = a;
UnusedObjectBuilder({required int a}) : _a = a;
/// Finish building, and store into the [fbBuilder].
@override
@@ -129,6 +124,7 @@ class UnusedObjectBuilder extends fb.ObjectBuilder {
return fbBuilder.buffer;
}
}
class TableB {
TableB._(this._bc, this._bcOffset);
factory TableB(List<int> bytes) {
@@ -148,8 +144,7 @@ class TableB {
return 'TableB{a: ${a}}';
}
TableBT unpack() => TableBT(
a: a?.unpack());
TableBT unpack() => TableBT(a: a?.unpack());
static int pack(fb.Builder fbBuilder, TableBT? object) {
if (object == null) return 0;
@@ -160,8 +155,7 @@ class TableB {
class TableBT implements fb.Packable {
TableAT? a;
TableBT({
this.a});
TableBT({this.a});
@override
int pack(fb.Builder fbBuilder) {
@@ -181,8 +175,7 @@ class _TableBReader extends fb.TableReader<TableB> {
const _TableBReader();
@override
TableB createObject(fb.BufferContext bc, int offset) =>
TableB._(bc, offset);
TableB createObject(fb.BufferContext bc, int offset) => TableB._(bc, offset);
}
class TableBBuilder {
@@ -207,10 +200,7 @@ class TableBBuilder {
class TableBObjectBuilder extends fb.ObjectBuilder {
final TableAObjectBuilder? _a;
TableBObjectBuilder({
TableAObjectBuilder? a,
})
: _a = a;
TableBObjectBuilder({TableAObjectBuilder? a}) : _a = a;
/// Finish building, and store into the [fbBuilder].
@override

View File

@@ -4,12 +4,12 @@
library my_game.example2;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_test_my_game_generated.dart' as my_game;
import './monster_test_my_game.example_generated.dart' as my_game_example;
import './include_test1_generated.dart';
import './monster_test_my_game.example_generated.dart' as my_game_example;
import './monster_test_my_game_generated.dart' as my_game;
class Monster {
Monster._(this._bc, this._bcOffset);
@@ -23,7 +23,6 @@ class Monster {
final fb.BufferContext _bc;
final int _bcOffset;
@override
String toString() {
return 'Monster{}';
@@ -54,12 +53,11 @@ class _MonsterReader extends fb.TableReader<Monster> {
const _MonsterReader();
@override
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
Monster createObject(fb.BufferContext bc, int offset) =>
Monster._(bc, offset);
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
MonsterObjectBuilder();
/// Finish building, and store into the [fbBuilder].

File diff suppressed because it is too large Load Diff

View File

@@ -4,12 +4,12 @@
library my_game;
import 'dart:typed_data' show Uint8List;
import 'package:flat_buffers/flat_buffers.dart' as fb;
import './monster_test_my_game.example_generated.dart' as my_game_example;
import './monster_test_my_game.example2_generated.dart' as my_game_example2;
import './include_test1_generated.dart';
import './monster_test_my_game.example2_generated.dart' as my_game_example2;
import './monster_test_my_game.example_generated.dart' as my_game_example;
class InParentNamespace {
InParentNamespace._(this._bc, this._bcOffset);
@@ -23,7 +23,6 @@ class InParentNamespace {
final fb.BufferContext _bc;
final int _bcOffset;
@override
String toString() {
return 'InParentNamespace{}';
@@ -54,12 +53,11 @@ class _InParentNamespaceReader extends fb.TableReader<InParentNamespace> {
const _InParentNamespaceReader();
@override
InParentNamespace createObject(fb.BufferContext bc, int offset) =>
InParentNamespace._(bc, offset);
InParentNamespace createObject(fb.BufferContext bc, int offset) =>
InParentNamespace._(bc, offset);
}
class InParentNamespaceObjectBuilder extends fb.ObjectBuilder {
InParentNamespaceObjectBuilder();
/// Finish building, and store into the [fbBuilder].

View File

@@ -28,12 +28,12 @@ func ReadResponse(r *http.Response) {
res := net.GetRootAsResponse(body, 0)
player := res.Player(nil)
fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp())
}
func main() {
body := RequestBody()
body := RequestBody()
req, err := http.NewRequest("POST", "http://localhost:8080/echo", body)
if err != nil {
fmt.Println(err)

View File

@@ -8,7 +8,7 @@ import (
type WarriorT struct {
Name string `json:"name"`
Hp uint32 `json:"hp"`
Hp uint32 `json:"hp"`
}
func (t *WarriorT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT {

View File

@@ -104,15 +104,18 @@ func (b *Builder) StartObject(numfields int) {
// logically-equal vtables will be deduplicated.
//
// A vtable has the following format:
// <VOffsetT: size of the vtable in bytes, including this value>
// <VOffsetT: size of the object in bytes, including the vtable offset>
// <VOffsetT: offset for a field> * N, where N is the number of fields in
// the schema for this type. Includes deprecated fields.
//
// <VOffsetT: size of the vtable in bytes, including this value>
// <VOffsetT: size of the object in bytes, including the vtable offset>
// <VOffsetT: offset for a field> * N, where N is the number of fields in
// the schema for this type. Includes deprecated fields.
//
// Thus, a vtable is made of 2 + N elements, each SizeVOffsetT bytes wide.
//
// An object has the following format:
// <SOffsetT: offset to this object's vtable (may be negative)>
// <byte: data>+
//
// <SOffsetT: offset to this object's vtable (may be negative)>
// <byte: data>+
func (b *Builder) WriteVtable() (n UOffsetT) {
// Prepend a zero scalar to the object. Later in this function we'll
// write an offset here that points to the object's vtable:
@@ -296,8 +299,9 @@ func (b *Builder) PrependUOffsetT(off UOffsetT) {
// StartVector initializes bookkeeping for writing a new vector.
//
// A vector has the following format:
// <UOffsetT: number of elements in this vector>
// <T: data>+, where T is the type of elements of this vector.
//
// <UOffsetT: number of elements in this vector>
// <T: data>+, where T is the type of elements of this vector.
func (b *Builder) StartVector(elemSize, numElems, alignment int) UOffsetT {
b.assertNotNested()
b.nested = true

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with C++ specifics
flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp")
# Wrap the golden flatc generator with C++ specifics
flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp")
def GenerateCpp():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with C# specifics
flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp")
# Wrap the golden flatc generator with C# specifics
flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp")
def GenerateCSharp():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Dart specifics
flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart")
# Wrap the golden flatc generator with Dart specifics
flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart")
def GenerateDart():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Go specifics
flatc_golden(options=["--go"] + options, schema=schema, prefix="go")
# Wrap the golden flatc generator with Go specifics
flatc_golden(options=["--go"] + options, schema=schema, prefix="go")
def GenerateGo():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -1,5 +1,5 @@
import sys
from pathlib import Path
import sys
# Get the path where this script is located so we can invoke the script from
# any directory and have the paths work correctly.
@@ -18,13 +18,13 @@ from scripts.util import flatc
def flatc_golden(options, schema, prefix):
# wrap the generic flatc call with specifis for these goldens.
flatc(
options=options,
# where the files are generated, typically the language (e.g. "cpp").
prefix=prefix,
# The schema are relative to the schema directory.
schema=str(Path(schema_path, schema)),
# Run flatc from this location.
cwd=script_path,
)
# wrap the generic flatc call with specifis for these goldens.
flatc(
options=options,
# where the files are generated, typically the language (e.g. "cpp").
prefix=prefix,
# The schema are relative to the schema directory.
schema=str(Path(schema_path, schema)),
# Run flatc from this location.
cwd=script_path,
)

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Java specifics
flatc_golden(options=["--java"] + options, schema=schema, prefix="java")
# Wrap the golden flatc generator with Java specifics
flatc_golden(options=["--java"] + options, schema=schema, prefix="java")
def GenerateJava():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Kotlin specifics
flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin")
# Wrap the golden flatc generator with Kotlin specifics
flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin")
def GenerateKotlin():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Lobster specifics
flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster")
# Wrap the golden flatc generator with Lobster specifics
flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster")
def GenerateLobster():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Lua specifics
flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua")
# Wrap the golden flatc generator with Lua specifics
flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua")
def GenerateLua():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Nim specifics
flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim")
# Wrap the golden flatc generator with Nim specifics
flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim")
def GenerateNim():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with PHP specifics
flatc_golden(options=["--php"] + options, schema=schema, prefix="php")
# Wrap the golden flatc generator with PHP specifics
flatc_golden(options=["--php"] + options, schema=schema, prefix="php")
def GeneratePhp():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Python specifics
flatc_golden(options=["--python"] + options, schema=schema, prefix="py")
# Wrap the golden flatc generator with Python specifics
flatc_golden(options=["--python"] + options, schema=schema, prefix="py")
def GeneratePython():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Rust specifics
flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust")
# Wrap the golden flatc generator with Rust specifics
flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust")
def GenerateRust():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift")
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift")
def GenerateSwift():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -2,5 +2,5 @@
/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */
export { Galaxy } from './galaxy.js';
export { Universe } from './universe.js';
export {Galaxy} from './galaxy.js';
export {Universe} from './universe.js';

View File

@@ -2,9 +2,9 @@ from golden_utils import flatc_golden
def flatc(options, schema):
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts")
# Wrap the golden flatc generator with Swift specifics
flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts")
def GenerateTs():
flatc([], "basic.fbs")
flatc([], "basic.fbs")

View File

@@ -1,40 +1,46 @@
import sys
import argparse
import sys
import grpc
sys.path.insert(0, '../../../../../flatbuffers/python')
sys.path.insert(0, "../../../../../flatbuffers/python")
import flatbuffers
from models import HelloReply, HelloRequest, greeter_grpc_fb
parser = argparse.ArgumentParser()
parser.add_argument("port", help="server port to connect to", default=3000)
parser.add_argument("name", help="name to be sent to server", default="flatbuffers")
parser.add_argument(
"name", help="name to be sent to server", default="flatbuffers"
)
def say_hello(stub, hello_request):
reply = stub.SayHello(hello_request)
r = HelloReply.HelloReply.GetRootAs(reply)
print(r.Message())
reply = stub.SayHello(hello_request)
r = HelloReply.HelloReply.GetRootAs(reply)
print(r.Message())
def say_many_hellos(stub, hello_request):
greetings = stub.SayManyHellos(hello_request)
for greeting in greetings:
r = HelloReply.HelloReply.GetRootAs(greeting)
print(r.Message())
greetings = stub.SayManyHellos(hello_request)
for greeting in greetings:
r = HelloReply.HelloReply.GetRootAs(greeting)
print(r.Message())
def main():
args = parser.parse_args()
args = parser.parse_args()
with grpc.insecure_channel('localhost:' + args.port) as channel:
builder = flatbuffers.Builder()
ind = builder.CreateString(args.name)
HelloRequest.HelloRequestStart(builder)
HelloRequest.HelloRequestAddName(builder, ind)
root = HelloRequest.HelloRequestEnd(builder)
builder.Finish(root)
output = bytes(builder.Output())
stub = greeter_grpc_fb.GreeterStub(channel)
say_hello(stub, output)
say_many_hellos(stub, output)
with grpc.insecure_channel("localhost:" + args.port) as channel:
builder = flatbuffers.Builder()
ind = builder.CreateString(args.name)
HelloRequest.HelloRequestStart(builder)
HelloRequest.HelloRequestAddName(builder, ind)
root = HelloRequest.HelloRequestEnd(builder)
builder.Finish(root)
output = bytes(builder.Output())
stub = greeter_grpc_fb.GreeterStub(channel)
say_hello(stub, output)
say_many_hellos(stub, output)
main()
main()

View File

@@ -2,30 +2,29 @@
import flatbuffers
import grpc
from models.HelloReply import HelloReply
from models.HelloRequest import HelloRequest
class GreeterStub(object):
'''Interface exported by the server.'''
"""Interface exported by the server."""
def __init__(self, channel):
'''Constructor.
"""Constructor.
Args:
channel: A grpc.Channel.
'''
"""
self.SayHello = channel.unary_unary(
method='/models.Greeter/SayHello')
self.SayHello = channel.unary_unary(method='/models.Greeter/SayHello')
self.SayManyHellos = channel.unary_stream(
method='/models.Greeter/SayManyHellos')
method='/models.Greeter/SayManyHellos'
)
class GreeterServicer(object):
'''Interface exported by the server.'''
"""Interface exported by the server."""
def SayHello(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
@@ -40,15 +39,14 @@ class GreeterServicer(object):
def add_GreeterServicer_to_server(servicer, server):
rpc_method_handlers = {
'SayHello': grpc.unary_unary_rpc_method_handler(
servicer.SayHello),
'SayManyHellos': grpc.unary_stream_rpc_method_handler(
servicer.SayManyHellos),
'SayHello': grpc.unary_unary_rpc_method_handler(servicer.SayHello),
'SayManyHellos': grpc.unary_stream_rpc_method_handler(
servicer.SayManyHellos
),
}
generic_handler = grpc.method_handlers_generic_handler(
'models.Greeter', rpc_method_handlers)
'models.Greeter', rpc_method_handlers
)
server.add_generic_rpc_handlers((generic_handler,))

View File

@@ -1,9 +1,9 @@
from concurrent import futures
import sys
import argparse
from concurrent import futures
import sys
import grpc
sys.path.insert(0, '../../../../../flatbuffers/python')
sys.path.insert(0, "../../../../../flatbuffers/python")
import flatbuffers
from models import HelloReply, HelloRequest, greeter_grpc_fb
@@ -11,47 +11,48 @@ from models import HelloReply, HelloRequest, greeter_grpc_fb
parser = argparse.ArgumentParser()
parser.add_argument("port", help="server on port", default=3000)
def build_reply(message):
builder = flatbuffers.Builder()
ind = builder.CreateString(message)
HelloReply.HelloReplyStart(builder)
HelloReply.HelloReplyAddMessage(builder, ind)
root = HelloReply.HelloReplyEnd(builder)
builder.Finish(root)
return bytes(builder.Output())
builder = flatbuffers.Builder()
ind = builder.CreateString(message)
HelloReply.HelloReplyStart(builder)
HelloReply.HelloReplyAddMessage(builder, ind)
root = HelloReply.HelloReplyEnd(builder)
builder.Finish(root)
return bytes(builder.Output())
class GreeterServicer(greeter_grpc_fb.GreeterServicer):
def __init__(self):
self.greetings = ["Hi", "Hallo", "Ciao"]
def __init__(self):
self.greetings = ["Hi", "Hallo", "Ciao"]
def SayHello(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
return build_reply("welcome " + reply.decode('UTF-8'))
def SayHello(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
return build_reply("welcome " + reply.decode("UTF-8"))
def SayManyHellos(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
def SayManyHellos(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
for greeting in self.greetings:
print(type(reply))
yield build_reply(greeting + " " + reply.decode("UTF-8"))
for greeting in self.greetings:
print(type(reply))
yield build_reply(greeting + " " + reply.decode('UTF-8'))
def serve():
args = parser.parse_args()
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
greeter_grpc_fb.add_GreeterServicer_to_server(
GreeterServicer(), server
)
server.add_insecure_port('[::]:' + args.port)
server.start()
server.wait_for_termination()
args = parser.parse_args()
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
greeter_grpc_fb.add_GreeterServicer_to_server(GreeterServicer(), server)
server.add_insecure_port("[::]:" + args.port)
server.start()
server.wait_for_termination()
if __name__ == '__main__':
serve()
if __name__ == "__main__":
serve()

View File

@@ -37,7 +37,8 @@ func greet(name: String, client greeter: models_GreeterServiceClient) {
builder.finish(offset: root)
// Make the RPC call to the server.
let sayHello = greeter
let sayHello =
greeter
.SayHello(Message<models_HelloRequest>(builder: &builder))
// wait() on the response to stop the program from exiting before the response is received.
@@ -76,7 +77,7 @@ func main(args: [String]) {
print("Usage: PORT [NAME]")
exit(1)
case let (.some(port), name):
case (.some(let port), let name):
// Setup an `EventLoopGroup` for the connection to run on.
//
// See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups

View File

@@ -32,7 +32,8 @@ class Greeter: models_GreeterProvider {
func SayHello(
request: Message<models_HelloRequest>,
context: StatusOnlyCallContext)
context: StatusOnlyCallContext
)
-> EventLoopFuture<Message<models_HelloReply>>
{
let recipient = request.object.name ?? "Stranger"
@@ -47,12 +48,14 @@ class Greeter: models_GreeterProvider {
func SayManyHellos(
request: Message<models_HelloRequest>,
context: StreamingResponseCallContext<Message<models_HelloReply>>)
context: StreamingResponseCallContext<Message<models_HelloReply>>
)
-> EventLoopFuture<GRPCStatus>
{
for name in greetings {
var builder = FlatBufferBuilder()
let off = builder
let off =
builder
.create(string: "\(name) \(request.object.name ?? "Unknown")")
let root = models_HelloReply.createHelloReply(
&builder,

View File

@@ -1,34 +1,39 @@
import * as grpc from '@grpc/grpc-js';
import * as flatbuffers from 'flatbuffers';
import { HelloReply } from './models/hello-reply';
import { HelloRequest } from './models/hello-request';
import { GreeterClient } from './greeter_grpc';
import {GreeterClient} from './greeter_grpc';
import {HelloReply} from './models/hello-reply';
import {HelloRequest} from './models/hello-request';
async function main(PORT: Number, name: string) {
const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure());
const builder = new flatbuffers.Builder();
const offset = builder.createString(name);
const root = HelloRequest.createHelloRequest(builder, offset);
builder.finish(root);
const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
const client = new GreeterClient(
`localhost:${PORT}`,
grpc.credentials.createInsecure(),
);
const builder = new flatbuffers.Builder();
const offset = builder.createString(name);
const root = HelloRequest.createHelloRequest(builder, offset);
builder.finish(root);
const buffer = HelloRequest.getRootAsHelloRequest(
new flatbuffers.ByteBuffer(builder.asUint8Array()),
);
client.SayHello(buffer, (err, response) => {
console.log(response.message());
});
client.SayHello(buffer, (err, response) => {
console.log(response.message());
});
const data = client.SayManyHellos(buffer, null);
const data = client.SayManyHellos(buffer, null);
data.on('data', (data) => {
console.log(data.message());
});
data.on('data', (data) => {
console.log(data.message());
});
}
const args = process.argv.slice(2)
const args = process.argv.slice(2);
const PORT = Number(args[0]);
const name: string = args[1] ?? "flatbuffers";
const name: string = args[1] ?? 'flatbuffers';
if (PORT) {
main(PORT, name);
main(PORT, name);
} else {
throw new Error("Requires a valid port number.")
}
throw new Error('Requires a valid port number.');
}

View File

@@ -1,4 +1,4 @@
// automatically generated by the FlatBuffers compiler, do not modify
export { HelloReply } from './models/hello-reply.js';
export { HelloRequest } from './models/hello-request.js';
export {HelloReply} from './models/hello-reply.js';
export {HelloRequest} from './models/hello-request.js';

View File

@@ -1,49 +1,63 @@
import * as grpc from '@grpc/grpc-js';
import * as flatbuffers from 'flatbuffers';
import { HelloReply } from './models/hello-reply';
import { HelloRequest } from './models/hello-request';
import { IGreeterServer, GreeterService } from './greeter_grpc';
import {GreeterService, IGreeterServer} from './greeter_grpc';
import {HelloReply} from './models/hello-reply';
import {HelloRequest} from './models/hello-request';
const greeter: IGreeterServer = {
SayHello(call: grpc.ServerUnaryCall<HelloRequest, HelloReply>, callback: grpc.sendUnaryData<HelloReply>): void {
console.log(`SayHello ${call.request.name()}`);
const builder = new flatbuffers.Builder();
const offset = builder.createString(`welcome ${call.request.name()}`);
const root = HelloReply.createHelloReply(builder, offset);
builder.finish(root);
callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
},
async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest, HelloReply>): Promise<void> {
const name = call.request.name();
console.log(`${call.request.name()} saying hi in different langagues`);
['Hi', 'Hallo', 'Ciao'].forEach(element => {
const builder = new flatbuffers.Builder();
const offset = builder.createString(`${element} ${name}`);
const root = HelloReply.createHelloReply(builder, offset);
builder.finish(root);
call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
});
call.end();
}
}
SayHello(
call: grpc.ServerUnaryCall<HelloRequest, HelloReply>,
callback: grpc.sendUnaryData<HelloReply>,
): void {
console.log(`SayHello ${call.request.name()}`);
const builder = new flatbuffers.Builder();
const offset = builder.createString(`welcome ${call.request.name()}`);
const root = HelloReply.createHelloReply(builder, offset);
builder.finish(root);
callback(
null,
HelloReply.getRootAsHelloReply(
new flatbuffers.ByteBuffer(builder.asUint8Array()),
),
);
},
async SayManyHellos(
call: grpc.ServerWritableStream<HelloRequest, HelloReply>,
): Promise<void> {
const name = call.request.name();
console.log(`${call.request.name()} saying hi in different langagues`);
['Hi', 'Hallo', 'Ciao'].forEach((element) => {
const builder = new flatbuffers.Builder();
const offset = builder.createString(`${element} ${name}`);
const root = HelloReply.createHelloReply(builder, offset);
builder.finish(root);
call.write(
HelloReply.getRootAsHelloReply(
new flatbuffers.ByteBuffer(builder.asUint8Array()),
),
);
});
call.end();
},
};
function serve(): void {
const PORT = 3000;
const server = new grpc.Server();
server.addService(GreeterService, greeter);
console.log(`Listening on ${PORT}`);
server.bindAsync(
`localhost:${PORT}`,
grpc.ServerCredentials.createInsecure(),
(err: Error | null, port: number) => {
if (err) {
console.error(`Server error: ${err.message}`);
} else {
console.log(`Server bound on port: ${port}`);
server.start();
}
}
);
const PORT = 3000;
const server = new grpc.Server();
server.addService(GreeterService, greeter);
console.log(`Listening on ${PORT}`);
server.bindAsync(
`localhost:${PORT}`,
grpc.ServerCredentials.createInsecure(),
(err: Error | null, port: number) => {
if (err) {
console.error(`Server error: ${err.message}`);
} else {
console.log(`Server bound on port: ${port}`);
server.start();
}
},
);
}
serve();
serve();

View File

@@ -19,99 +19,99 @@ import com.google.flatbuffers.Table;
import io.grpc.Drainable;
import io.grpc.KnownLength;
import io.grpc.MethodDescriptor;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import javax.annotation.Nullable;
public class FlatbuffersUtils {
abstract public static class FBExtactor <T extends Table> {
T extract (InputStream stream) throws IOException {
if (stream instanceof KnownLength) {
int size = stream.available();
ByteBuffer buffer = ByteBuffer.allocate(size);
stream.read(buffer.array());
return extract(buffer);
} else
throw new RuntimeException("The class " + stream.getClass().getCanonicalName() + " does not extend from KnownLength ");
}
public abstract T extract(ByteBuffer buffer);
public abstract static class FBExtactor<T extends Table> {
T extract(InputStream stream) throws IOException {
if (stream instanceof KnownLength) {
int size = stream.available();
ByteBuffer buffer = ByteBuffer.allocate(size);
stream.read(buffer.array());
return extract(buffer);
} else
throw new RuntimeException(
"The class "
+ stream.getClass().getCanonicalName()
+ " does not extend from KnownLength ");
}
static class FBInputStream extends InputStream implements Drainable, KnownLength {
private final ByteBuffer buffer;
private final int size;
@Nullable private ByteArrayInputStream inputStream;
public abstract T extract(ByteBuffer buffer);
}
FBInputStream(ByteBuffer buffer) {
this.buffer = buffer;
this.size = buffer.remaining();
}
private void makeStreamIfNotAlready() {
if (inputStream == null)
inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size);
}
@Override
public int drainTo(OutputStream target) throws IOException {
target.write(buffer.array(), buffer.position(), size);
return size;
}
@Override
public int read() throws IOException {
makeStreamIfNotAlready();
return inputStream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
makeStreamIfNotAlready();
if (inputStream == null) {
if (len >= size) {
System.arraycopy(buffer.array(), buffer.position(), b, off, size);
return size;
} else {
makeStreamIfNotAlready();
return inputStream.read(b, off, len);
}
} else
return inputStream.read(b, off, len);
}
@Override
public int available() throws IOException {
return inputStream == null ? size : inputStream.available();
}
static class FBInputStream extends InputStream implements Drainable, KnownLength {
private final ByteBuffer buffer;
private final int size;
@Nullable private ByteArrayInputStream inputStream;
FBInputStream(ByteBuffer buffer) {
this.buffer = buffer;
this.size = buffer.remaining();
}
public static <T extends Table> MethodDescriptor.Marshaller<T> marshaller(final Class<T> clazz, final FBExtactor<T> extractor) {
return new MethodDescriptor.ReflectableMarshaller<T>() {
@Override
public Class<T> getMessageClass() {
return clazz;
}
@Override
public InputStream stream(T value) {
return new FBInputStream (value.getByteBuffer());
}
@Override
public T parse(InputStream stream) {
try {
return extractor.extract(stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
private void makeStreamIfNotAlready() {
if (inputStream == null)
inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size);
}
@Override
public int drainTo(OutputStream target) throws IOException {
target.write(buffer.array(), buffer.position(), size);
return size;
}
@Override
public int read() throws IOException {
makeStreamIfNotAlready();
return inputStream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
makeStreamIfNotAlready();
if (inputStream == null) {
if (len >= size) {
System.arraycopy(buffer.array(), buffer.position(), b, off, size);
return size;
} else {
makeStreamIfNotAlready();
return inputStream.read(b, off, len);
}
} else return inputStream.read(b, off, len);
}
@Override
public int available() throws IOException {
return inputStream == null ? size : inputStream.available();
}
}
public static <T extends Table> MethodDescriptor.Marshaller<T> marshaller(
final Class<T> clazz, final FBExtactor<T> extractor) {
return new MethodDescriptor.ReflectableMarshaller<T>() {
@Override
public Class<T> getMessageClass() {
return clazz;
}
@Override
public InputStream stream(T value) {
return new FBInputStream(value.getByteBuffer());
}
@Override
public T parse(InputStream stream) {
try {
return extractor.extract(stream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
}
}

View File

@@ -8,21 +8,22 @@
namespace grpc_cpp_generator {
namespace {
template<class T> static grpc::string as_string(T x) {
template <class T>
static grpc::string as_string(T x) {
std::ostringstream out;
out << x;
return out.str();
}
static inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
static inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
return method->ClientStreaming() && !method->ServerStreaming();
}
static inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
static inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
return !method->ClientStreaming() && method->ServerStreaming();
}
static grpc::string FilenameIdentifier(const grpc::string &filename) {
static grpc::string FilenameIdentifier(const grpc::string& filename) {
grpc::string result;
for (unsigned i = 0; i < filename.size(); i++) {
char c = filename[i];
@@ -38,22 +39,25 @@ static grpc::string FilenameIdentifier(const grpc::string &filename) {
return result;
}
template<class T, size_t N> static T *array_end(T (&array)[N]) {
template <class T, size_t N>
static T* array_end(T (&array)[N]) {
return array + N;
}
static void PrintIncludes(grpc_generator::Printer *printer,
const std::vector<grpc::string> &headers,
const Parameters &params) {
static void PrintIncludes(grpc_generator::Printer* printer,
const std::vector<grpc::string>& headers,
const Parameters& params) {
std::map<grpc::string, grpc::string> vars;
vars["l"] = params.use_system_headers ? '<' : '"';
vars["r"] = params.use_system_headers ? '>' : '"';
auto &s = params.grpc_search_path;
auto& s = params.grpc_search_path;
if (!s.empty()) {
vars["l"] += s;
if (s[s.size() - 1] != '/') { vars["l"] += '/'; }
if (s[s.size() - 1] != '/') {
vars["l"] += '/';
}
}
for (auto i = headers.begin(); i != headers.end(); i++) {
@@ -62,12 +66,11 @@ static void PrintIncludes(grpc_generator::Printer *printer,
}
if (params.generate_callback_api) {
// Callback API headers (guarded later by feature macro in emitted code).
static const char *cb_headers[] = {
"grpcpp/impl/codegen/callback_common.h",
"grpcpp/impl/codegen/server_callback_handlers.h",
"grpcpp/support/client_callback.h"
};
for (auto &h : cb_headers) {
static const char* cb_headers[] = {
"grpcpp/impl/codegen/callback_common.h",
"grpcpp/impl/codegen/server_callback_handlers.h",
"grpcpp/support/client_callback.h"};
for (auto& h : cb_headers) {
vars["h"] = h;
printer->Print(vars, "#include $l$$h$$r$\n");
}
@@ -76,8 +79,8 @@ static void PrintIncludes(grpc_generator::Printer *printer,
} // namespace
grpc::string GetHeaderPrologue(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetHeaderPrologue(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -108,25 +111,24 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file,
return output;
}
grpc::string GetHeaderIncludes(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetHeaderIncludes(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
auto printer = file->CreatePrinter(&output);
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/async_unary_call.h",
"grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/proto_utils.h",
"grpcpp/impl/codegen/rpc_method.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/status.h",
"grpcpp/impl/codegen/stub_options.h",
"grpcpp/impl/codegen/sync_stream.h"
};
static const char* headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/async_unary_call.h",
"grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/proto_utils.h",
"grpcpp/impl/codegen/rpc_method.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/status.h",
"grpcpp/impl/codegen/stub_options.h",
"grpcpp/impl/codegen/sync_stream.h"};
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
printer->Print(vars, "\n");
@@ -153,8 +155,8 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file,
namespace {
static void PrintHeaderClientMethodInterfaces(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars, bool is_public) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars, bool is_public) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -163,8 +165,8 @@ static void PrintHeaderClientMethodInterfaces(
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
{ "PrepareAsync", "", "" } };
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
{"PrepareAsync", "", ""}};
if (is_public) {
if (method->NoStreaming()) {
@@ -174,7 +176,7 @@ static void PrintHeaderClientMethodInterfaces(
"const $Request$& request, $Response$* response) = 0;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -207,7 +209,7 @@ static void PrintHeaderClientMethodInterfaces(
printer->Print("}\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -242,7 +244,7 @@ static void PrintHeaderClientMethodInterfaces(
printer->Print("}\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -276,7 +278,7 @@ static void PrintHeaderClientMethodInterfaces(
printer->Print("}\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -300,7 +302,7 @@ static void PrintHeaderClientMethodInterfaces(
if (method->NoStreaming()) {
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -317,7 +319,7 @@ static void PrintHeaderClientMethodInterfaces(
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -335,7 +337,7 @@ static void PrintHeaderClientMethodInterfaces(
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -352,7 +354,7 @@ static void PrintHeaderClientMethodInterfaces(
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
printer->Print(
@@ -366,9 +368,9 @@ static void PrintHeaderClientMethodInterfaces(
}
}
static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars,
static void PrintHeaderClientMethod(grpc_generator::Printer* printer,
const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars,
bool is_public) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
@@ -377,8 +379,8 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
grpc::string prefix;
grpc::string method_params; // extra arguments to method
grpc::string raw_args; // extra arguments to raw version of method
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
{ "PrepareAsync", "", "" } };
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
{"PrepareAsync", "", ""}};
if (is_public) {
if (method->NoStreaming()) {
@@ -404,7 +406,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -432,15 +434,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
"($Method$Raw(context, response));\n");
printer->Outdent();
printer->Print("}\n");
if ((*vars)["generate_callback_api"] == "1") {
printer->Print(*vars, "// Client streaming callback reactor entry.\n");
printer->Print(
*vars,
"void async_$Method$(::grpc::ClientContext* context, $Response$* response, ::grpc::ClientWriteReactor< $Request$ >* reactor);\n");
}
if ((*vars)["generate_callback_api"] == "1") {
printer->Print(*vars, "// Client streaming callback reactor entry.\n");
printer->Print(
*vars,
"void async_$Method$(::grpc::ClientContext* context, $Response$* "
"response, ::grpc::ClientWriteReactor< $Request$ >* reactor);\n");
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -474,11 +477,13 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
if ((*vars)["generate_callback_api"] == "1") {
printer->Print(*vars, "// Server streaming callback reactor entry.\n");
printer->Print(*vars,
"void async_$Method$(::grpc::ClientContext* context, const $Request$& request, ::grpc::ClientReadReactor< $Response$ >* reactor);\n");
"void async_$Method$(::grpc::ClientContext* context, "
"const $Request$& request, ::grpc::ClientReadReactor< "
"$Response$ >* reactor);\n");
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -508,15 +513,17 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
"$Method$Raw(context));\n");
printer->Outdent();
printer->Print("}\n");
if ((*vars)["generate_callback_api"] == "1") {
printer->Print(*vars, "// Bidirectional streaming callback reactor entry.\n");
printer->Print(
*vars,
"void async_$Method$(::grpc::ClientContext* context, ::grpc::ClientBidiReactor< $Request$, $Response$ >* reactor);\n");
}
if ((*vars)["generate_callback_api"] == "1") {
printer->Print(*vars,
"// Bidirectional streaming callback reactor entry.\n");
printer->Print(
*vars,
"void async_$Method$(::grpc::ClientContext* context, "
"::grpc::ClientBidiReactor< $Request$, $Response$ >* reactor);\n");
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -539,7 +546,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
if (method->NoStreaming()) {
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -559,7 +566,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
"override;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -576,7 +583,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
" override;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -592,7 +599,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
"$Method$Raw(::grpc::ClientContext* context) override;\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
@@ -607,16 +614,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
}
static void PrintHeaderClientMethodData(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
printer->Print(*vars,
"const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
}
static void PrintHeaderServerMethodSync(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -649,8 +656,8 @@ static void PrintHeaderServerMethodSync(
}
static void PrintHeaderServerMethodAsync(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -765,8 +772,8 @@ static void PrintHeaderServerMethodAsync(
}
static void PrintHeaderServerMethodStreamedUnary(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -816,8 +823,8 @@ static void PrintHeaderServerMethodStreamedUnary(
}
static void PrintHeaderServerMethodSplitStreaming(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -869,8 +876,8 @@ static void PrintHeaderServerMethodSplitStreaming(
}
static void PrintHeaderServerMethodGeneric(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -939,9 +946,9 @@ static void PrintHeaderServerMethodGeneric(
printer->Print(*vars, "};\n");
}
static void PrintHeaderService(grpc_generator::Printer *printer,
const grpc_generator::Service *service,
std::map<grpc::string, grpc::string> *vars) {
static void PrintHeaderService(grpc_generator::Printer* printer,
const grpc_generator::Service* service,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Service"] = service->name();
printer->Print(service->GetLeadingComments("//").c_str());
@@ -1036,7 +1043,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); }
for (int i = 0; i < service->method_count(); ++i) {
printer->Print(" >");
}
printer->Print(" AsyncService;\n");
// Server side - Generic
@@ -1061,7 +1070,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
}
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
if (service->method(i)->NoStreaming()) { printer->Print(" >"); }
if (service->method(i)->NoStreaming()) {
printer->Print(" >");
}
}
printer->Print(" StreamedUnaryService;\n");
@@ -1083,7 +1094,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
printer->Print("Service");
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); }
if (ServerOnlyStreaming(method.get())) {
printer->Print(" >");
}
}
printer->Print(" SplitStreamedService;\n");
@@ -1117,10 +1130,10 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
if ((*vars)["generate_callback_api"] == "1") {
(*vars)["Service"] = service->name();
printer->Print("\n#if defined(GRPC_CALLBACK_API_NONEXPERIMENTAL)\n");
printer->Print(*vars,
"class $Service$::CallbackService : public ::grpc::Service "
"{\n public:\n CallbackService();\n virtual "
"~CallbackService();\n");
printer->Print(*vars,
"class $Service$::CallbackService : public ::grpc::Service "
"{\n public:\n CallbackService();\n virtual "
"~CallbackService();\n");
printer->Indent();
for (int i = 0; i < service->method_count(); ++i) {
auto m = service->method(i);
@@ -1158,8 +1171,8 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
} // namespace
grpc::string GetHeaderServices(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetHeaderServices(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1168,7 +1181,9 @@ grpc::string GetHeaderServices(grpc_generator::File *file,
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
if (!file->package().empty()) { vars["Package"].append("."); }
if (!file->package().empty()) {
vars["Package"].append(".");
}
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
@@ -1192,8 +1207,8 @@ grpc::string GetHeaderServices(grpc_generator::File *file,
return output;
}
grpc::string GetHeaderEpilogue(grpc_generator::File *file,
const Parameters & /*params*/) {
grpc::string GetHeaderEpilogue(grpc_generator::File* file,
const Parameters& /*params*/) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1221,8 +1236,8 @@ grpc::string GetHeaderEpilogue(grpc_generator::File *file,
return output;
}
grpc::string GetSourcePrologue(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetSourcePrologue(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1247,24 +1262,23 @@ grpc::string GetSourcePrologue(grpc_generator::File *file,
return output;
}
grpc::string GetSourceIncludes(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetSourceIncludes(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
auto printer = file->CreatePrinter(&output);
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/async_unary_call.h",
"grpcpp/impl/codegen/channel_interface.h",
"grpcpp/impl/codegen/client_unary_call.h",
"grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/rpc_service_method.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/sync_stream.h"
};
static const char* headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/async_unary_call.h",
"grpcpp/impl/codegen/channel_interface.h",
"grpcpp/impl/codegen/client_unary_call.h",
"grpcpp/impl/codegen/method_handler.h",
"grpcpp/impl/codegen/rpc_service_method.h",
"grpcpp/impl/codegen/service_type.h",
"grpcpp/impl/codegen/sync_stream.h"};
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1285,8 +1299,8 @@ grpc::string GetSourceIncludes(grpc_generator::File *file,
namespace {
static void PrintSourceClientMethod(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -1295,8 +1309,8 @@ static void PrintSourceClientMethod(
grpc::string start; // bool literal expressed as string
grpc::string method_params; // extra arguments to method
grpc::string create_args; // extra arguments to creator
} async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" },
{ "PrepareAsync", "false", "", ", nullptr" } };
} async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
{"PrepareAsync", "false", "", ", nullptr"}};
if (method->NoStreaming()) {
printer->Print(*vars,
"::grpc::Status $ns$$Service$::Stub::$Method$("
@@ -1312,24 +1326,25 @@ static void PrintSourceClientMethod(
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
"context, const $Request$& request, $Response$* response, "
"std::function<void(::grpc::Status)> on_done) {\n");
printer->Print(*vars,
" ::grpc::internal::CallbackUnaryCall(channel_.get(), "
"rpcmethod_$Method$_, context, &request, response, "
"std::move(on_done));\n}\n\n");
printer->Print(*vars,
" ::grpc::internal::CallbackUnaryCall(channel_.get(), "
"rpcmethod_$Method$_, context, &request, response, "
"std::move(on_done));\n}\n\n");
printer->Print(
*vars,
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
"context, const $Request$& request, $Response$* response, "
"::grpc::ClientUnaryReactor* reactor) {\n");
printer->Print(
*vars,
" "
"::grpc::internal::ClientCallbackUnaryFactory::Create(channel_.get(),"
" rpcmethod_$Method$_, context, &request, response, reactor);\n}\n\n");
printer->Print(
*vars,
" "
"::grpc::internal::ClientCallbackUnaryFactory::Create(channel_.get(),"
" rpcmethod_$Method$_, context, &request, response, "
"reactor);\n}\n\n");
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
printer->Print(*vars,
@@ -1372,7 +1387,7 @@ static void PrintSourceClientMethod(
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1409,14 +1424,15 @@ static void PrintSourceClientMethod(
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
"context, const $Request$& request, ::grpc::ClientReadReactor< "
"$Response$ >* reactor) {\n");
printer->Print(*vars,
" ::grpc::internal::ClientCallbackReaderFactory< "
"$Response$ >::Create(channel_.get(), "
"rpcmethod_$Method$_, context, &request, reactor);\n}\n\n");
printer->Print(
*vars,
" ::grpc::internal::ClientCallbackReaderFactory< "
"$Response$ >::Create(channel_.get(), "
"rpcmethod_$Method$_, context, &request, reactor);\n}\n\n");
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1460,7 +1476,7 @@ static void PrintSourceClientMethod(
}
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncStart"] = async_prefix.start;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
@@ -1483,8 +1499,8 @@ static void PrintSourceClientMethod(
}
static void PrintSourceServerMethod(
grpc_generator::Printer *printer, const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
grpc_generator::Printer* printer, const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -1531,9 +1547,9 @@ static void PrintSourceServerMethod(
}
}
static void PrintSourceService(grpc_generator::Printer *printer,
const grpc_generator::Service *service,
std::map<grpc::string, grpc::string> *vars) {
static void PrintSourceService(grpc_generator::Printer* printer,
const grpc_generator::Service* service,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Service"] = service->name();
if (service->method_count() > 0) {
@@ -1660,47 +1676,54 @@ static void PrintSourceService(grpc_generator::Printer *printer,
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
if (method->NoStreaming()) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
" new ::grpc::internal::CallbackUnaryHandler<$Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, const $Request$* req, $Response$* resp) {\n"
" return this->$Method$(ctx, req, resp);\n"
" })));\n");
} else if (ClientOnlyStreaming(method.get())) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
" new ::grpc::internal::CallbackClientStreamingHandler<$Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, $Response$* resp) {\n"
" return this->$Method$(ctx, resp);\n"
" })));\n");
} else if (ServerOnlyStreaming(method.get())) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
" new ::grpc::internal::CallbackServerStreamingHandler<$Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, const $Request$* req) {\n"
" return this->$Method$(ctx, req);\n"
" })));\n");
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::BIDI_STREAMING,\n"
" new ::grpc::internal::CallbackBidiHandler<$Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx) {\n"
" return this->$Method$(ctx);\n"
" })));\n");
}
if (method->NoStreaming()) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
" new ::grpc::internal::CallbackUnaryHandler<$Request$, "
"$Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, const $Request$* "
"req, $Response$* resp) {\n"
" return this->$Method$(ctx, req, resp);\n"
" })));\n");
} else if (ClientOnlyStreaming(method.get())) {
printer->Print(*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
" new "
"::grpc::internal::CallbackClientStreamingHandler<$"
"Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, "
"$Response$* resp) {\n"
" return this->$Method$(ctx, resp);\n"
" })));\n");
} else if (ServerOnlyStreaming(method.get())) {
printer->Print(*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
" new "
"::grpc::internal::CallbackServerStreamingHandler<$"
"Request$, $Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx, const "
"$Request$* req) {\n"
" return this->$Method$(ctx, req);\n"
" })));\n");
} else if (method->BidiStreaming()) {
printer->Print(
*vars,
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
" $prefix$$Service$_method_names[$Idx$],\n"
" ::grpc::internal::RpcMethod::BIDI_STREAMING,\n"
" new ::grpc::internal::CallbackBidiHandler<$Request$, "
"$Response$>(\n"
" [this](::grpc::CallbackServerContext* ctx) {\n"
" return this->$Method$(ctx);\n"
" })));\n");
}
}
printer->Outdent();
printer->Print("}\n\n");
@@ -1751,8 +1774,8 @@ static void PrintSourceService(grpc_generator::Printer *printer,
} // namespace
grpc::string GetSourceServices(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetSourceServices(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1761,7 +1784,9 @@ grpc::string GetSourceServices(grpc_generator::File *file,
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
if (!file->package().empty()) { vars["Package"].append("."); }
if (!file->package().empty()) {
vars["Package"].append(".");
}
if (!params.services_namespace.empty()) {
vars["ns"] = params.services_namespace + "::";
vars["prefix"] = params.services_namespace;
@@ -1779,8 +1804,8 @@ grpc::string GetSourceServices(grpc_generator::File *file,
return output;
}
grpc::string GetSourceEpilogue(grpc_generator::File *file,
const Parameters & /*params*/) {
grpc::string GetSourceEpilogue(grpc_generator::File* file,
const Parameters& /*params*/) {
grpc::string temp;
if (!file->package().empty()) {
@@ -1797,8 +1822,8 @@ grpc::string GetSourceEpilogue(grpc_generator::File *file,
return temp;
}
grpc::string GetMockPrologue(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetMockPrologue(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1824,18 +1849,18 @@ grpc::string GetMockPrologue(grpc_generator::File *file,
}
// TODO(mmukhi): Add client-stream and completion-queue headers.
grpc::string GetMockIncludes(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetMockIncludes(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
auto printer = file->CreatePrinter(&output);
std::map<grpc::string, grpc::string> vars;
static const char *headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/sync_stream.h",
"gmock/gmock.h",
static const char* headers_strs[] = {
"grpcpp/impl/codegen/async_stream.h",
"grpcpp/impl/codegen/sync_stream.h",
"gmock/gmock.h",
};
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
PrintIncludes(printer.get(), headers, params);
@@ -1856,9 +1881,9 @@ grpc::string GetMockIncludes(grpc_generator::File *file,
namespace {
static void PrintMockClientMethods(grpc_generator::Printer *printer,
const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *vars) {
static void PrintMockClientMethods(grpc_generator::Printer* printer,
const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type_name();
(*vars)["Response"] = method->output_type_name();
@@ -1867,8 +1892,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
grpc::string prefix;
grpc::string method_params; // extra arguments to method
int extra_method_param_count;
} async_prefixes[] = { { "Async", ", void* tag", 1 },
{ "PrepareAsync", "", 0 } };
} async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
if (method->NoStreaming()) {
printer->Print(
@@ -1877,7 +1901,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
"const $Request$& request, $Response$* response));\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
printer->Print(
*vars,
@@ -1894,7 +1918,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
"(::grpc::ClientContext* context, $Response$* response));\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1913,7 +1937,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
"(::grpc::ClientContext* context, const $Request$& request));\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1933,7 +1957,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
"(::grpc::ClientContext* context));\n");
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
i++) {
auto &async_prefix = async_prefixes[i];
auto& async_prefix = async_prefixes[i];
(*vars)["AsyncPrefix"] = async_prefix.prefix;
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
(*vars)["MockArgs"] =
@@ -1948,9 +1972,9 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
}
}
static void PrintMockService(grpc_generator::Printer *printer,
const grpc_generator::Service *service,
std::map<grpc::string, grpc::string> *vars) {
static void PrintMockService(grpc_generator::Printer* printer,
const grpc_generator::Service* service,
std::map<grpc::string, grpc::string>* vars) {
(*vars)["Service"] = service->name();
printer->Print(*vars,
@@ -1966,8 +1990,8 @@ static void PrintMockService(grpc_generator::Printer *printer,
} // namespace
grpc::string GetMockServices(grpc_generator::File *file,
const Parameters &params) {
grpc::string GetMockServices(grpc_generator::File* file,
const Parameters& params) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
@@ -1976,7 +2000,9 @@ grpc::string GetMockServices(grpc_generator::File *file,
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();
if (!file->package().empty()) { vars["Package"].append("."); }
if (!file->package().empty()) {
vars["Package"].append(".");
}
if (!params.services_namespace.empty()) {
vars["services_namespace"] = params.services_namespace;
@@ -1995,8 +2021,8 @@ grpc::string GetMockServices(grpc_generator::File *file,
return output;
}
grpc::string GetMockEpilogue(grpc_generator::File *file,
const Parameters & /*params*/) {
grpc::string GetMockEpilogue(grpc_generator::File* file,
const Parameters& /*params*/) {
grpc::string temp;
if (!file->package().empty()) {

View File

@@ -11,8 +11,8 @@
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
#include <string>
#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
@@ -42,68 +42,68 @@ struct Parameters {
};
// Return the prologue of the generated header file.
grpc::string GetHeaderPrologue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetHeaderPrologue(grpc_generator::File* file,
const Parameters& params);
// Return the includes needed for generated header file.
grpc::string GetHeaderIncludes(grpc_generator::File *file,
const Parameters &params);
grpc::string GetHeaderIncludes(grpc_generator::File* file,
const Parameters& params);
// Return the includes needed for generated source file.
grpc::string GetSourceIncludes(grpc_generator::File *file,
const Parameters &params);
grpc::string GetSourceIncludes(grpc_generator::File* file,
const Parameters& params);
// Return the epilogue of the generated header file.
grpc::string GetHeaderEpilogue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetHeaderEpilogue(grpc_generator::File* file,
const Parameters& params);
// Return the prologue of the generated source file.
grpc::string GetSourcePrologue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetSourcePrologue(grpc_generator::File* file,
const Parameters& params);
// Return the services for generated header file.
grpc::string GetHeaderServices(grpc_generator::File *file,
const Parameters &params);
grpc::string GetHeaderServices(grpc_generator::File* file,
const Parameters& params);
// Return the services for generated source file.
grpc::string GetSourceServices(grpc_generator::File *file,
const Parameters &params);
grpc::string GetSourceServices(grpc_generator::File* file,
const Parameters& params);
// Return the epilogue of the generated source file.
grpc::string GetSourceEpilogue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetSourceEpilogue(grpc_generator::File* file,
const Parameters& params);
// Return the prologue of the generated mock file.
grpc::string GetMockPrologue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockPrologue(grpc_generator::File* file,
const Parameters& params);
// Return the includes needed for generated mock file.
grpc::string GetMockIncludes(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockIncludes(grpc_generator::File* file,
const Parameters& params);
// Return the services for generated mock file.
grpc::string GetMockServices(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockServices(grpc_generator::File* file,
const Parameters& params);
// Return the epilogue of generated mock file.
grpc::string GetMockEpilogue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockEpilogue(grpc_generator::File* file,
const Parameters& params);
// Return the prologue of the generated mock file.
grpc::string GetMockPrologue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockPrologue(grpc_generator::File* file,
const Parameters& params);
// Return the includes needed for generated mock file.
grpc::string GetMockIncludes(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockIncludes(grpc_generator::File* file,
const Parameters& params);
// Return the services for generated mock file.
grpc::string GetMockServices(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockServices(grpc_generator::File* file,
const Parameters& params);
// Return the epilogue of generated mock file.
grpc::string GetMockEpilogue(grpc_generator::File *file,
const Parameters &params);
grpc::string GetMockEpilogue(grpc_generator::File* file,
const Parameters& params);
} // namespace grpc_cpp_generator

View File

@@ -4,17 +4,18 @@
#include <map>
#include <sstream>
template<class T> grpc::string as_string(T x) {
template <class T>
grpc::string as_string(T x) {
std::ostringstream out;
out << x;
return out.str();
}
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
return method->ClientStreaming() && !method->ServerStreaming();
}
inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
return !method->ClientStreaming() && method->ServerStreaming();
}
@@ -35,9 +36,9 @@ static grpc::string exportName(grpc::string s) {
return s;
}
static void GenerateError(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars,
const bool multiple_return = true) {
static void GenerateError(grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars,
const bool multiple_return = true) {
printer->Print(vars, "if $Error_Check$ {\n");
printer->Indent();
vars["Return"] = multiple_return ? "nil, err" : "err";
@@ -47,9 +48,9 @@ static void GenerateError(grpc_generator::Printer *printer,
}
// Generates imports for the service
static void GenerateImports(grpc_generator::File *file,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
static void GenerateImports(grpc_generator::File* file,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["filename"] = file->filename();
printer->Print("//Generated by gRPC Go plugin\n");
printer->Print("//If you make any local changes, they will be lost\n");
@@ -67,9 +68,9 @@ static void GenerateImports(grpc_generator::File *file,
}
// Generates Server method signature source
static void GenerateServerMethodSignature(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
static void GenerateServerMethodSignature(
const grpc_generator::Method* method, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] = method->get_input_type_name();
vars["Response"] = (vars["CustomMethodIO"] == "")
@@ -87,9 +88,9 @@ static void GenerateServerMethodSignature(const grpc_generator::Method *method,
}
}
static void GenerateServerMethod(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
static void GenerateServerMethod(const grpc_generator::Method* method,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] = method->get_input_type_name();
vars["Response"] = (vars["CustomMethodIO"] == "")
@@ -160,8 +161,12 @@ static void GenerateServerMethod(const grpc_generator::Method *method,
printer->Print(vars, "type $Service$_$Method$Server interface {\n");
printer->Indent();
if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); }
if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); }
if (genSend) {
printer->Print(vars, "Send(*$Response$) error\n");
}
if (genRecv) {
printer->Print(vars, "Recv() (*$Request$, error)\n");
}
if (genSendAndClose) {
printer->Print(vars, "SendAndClose(*$Response$) error\n");
}
@@ -205,9 +210,9 @@ static void GenerateServerMethod(const grpc_generator::Method *method,
}
// Generates Client method signature source
static void GenerateClientMethodSignature(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
static void GenerateClientMethodSignature(
const grpc_generator::Method* method, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["Method"] = exportName(method->name());
vars["Request"] =
", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name()
@@ -226,9 +231,9 @@ static void GenerateClientMethodSignature(const grpc_generator::Method *method,
}
// Generates Client method source
static void GenerateClientMethod(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> vars) {
static void GenerateClientMethod(const grpc_generator::Method* method,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
vars["Ending"] = " {\n";
GenerateClientMethodSignature(method, printer, vars);
@@ -277,8 +282,12 @@ static void GenerateClientMethod(const grpc_generator::Method *method,
// Stream interface
printer->Print(vars, "type $Service$_$Method$Client interface {\n");
printer->Indent();
if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); }
if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); }
if (genSend) {
printer->Print(vars, "Send(*$Request$) error\n");
}
if (genRecv) {
printer->Print(vars, "Recv() (*$Response$, error)\n");
}
if (genCloseAndRecv) {
printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
}
@@ -329,8 +338,8 @@ static void GenerateClientMethod(const grpc_generator::Method *method,
}
// Generates client API for the service
void GenerateService(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
void GenerateService(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string> vars) {
vars["Service"] = exportName(service->name());
// Client Interface
@@ -484,9 +493,9 @@ void GenerateService(const grpc_generator::Service *service,
} // namespace
// Returns source for the service
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters) {
grpc::string GenerateServiceSource(grpc_generator::File* file,
const grpc_generator::Service* service,
grpc_go_generator::Parameters* parameters) {
grpc::string out;
auto p = file->CreatePrinter(&out, '\t');
p->SetIndentationSize(1);

View File

@@ -24,9 +24,9 @@ struct Parameters {
};
// Return the source of the generated service file.
grpc::string GenerateServiceSource(grpc_generator::File *file,
const grpc_generator::Service *service,
grpc_go_generator::Parameters *parameters);
grpc::string GenerateServiceSource(grpc_generator::File* file,
const grpc_generator::Service* service,
grpc_go_generator::Parameters* parameters);
} // namespace grpc_go_generator

View File

@@ -28,11 +28,11 @@
// Stringify helpers used solely to cast GRPC_VERSION
#ifndef STR
# define STR(s) # s
#define STR(s) #s
#endif
#ifndef XSTR
# define XSTR(s) STR(s)
#define XSTR(s) STR(s)
#endif
typedef grpc_generator::Printer Printer;
@@ -46,8 +46,8 @@ namespace grpc_java_generator {
typedef std::string string;
namespace {
// Generates imports for the service
static void GenerateImports(grpc_generator::File *file,
grpc_generator::Printer *printer, VARS &vars) {
static void GenerateImports(grpc_generator::File* file,
grpc_generator::Printer* printer, VARS& vars) {
vars["filename"] = file->filename();
printer->Print(vars,
"//Generated by flatc compiler (version $flatc_version$)\n");
@@ -64,7 +64,7 @@ static void GenerateImports(grpc_generator::File *file,
// Adjust a method name prefix identifier to follow the JavaBean spec:
// - decapitalize the first letter
// - remove embedded underscores & capitalize the following letter
static string MixedLower(const string &word) {
static string MixedLower(const string& word) {
string w;
w += static_cast<string::value_type>(tolower(word[0]));
bool after_underscore = false;
@@ -84,7 +84,7 @@ static string MixedLower(const string &word) {
// - An underscore is inserted where a lower case letter is followed by an
// upper case letter.
// - All letters are converted to upper case
static string ToAllUpperCase(const string &word) {
static string ToAllUpperCase(const string& word) {
string w;
for (size_t i = 0; i < word.length(); ++i) {
w += static_cast<string::value_type>(toupper(word[i]));
@@ -95,49 +95,48 @@ static string ToAllUpperCase(const string &word) {
return w;
}
static inline string LowerMethodName(const MethodDescriptor *method) {
static inline string LowerMethodName(const MethodDescriptor* method) {
return MixedLower(method->name());
}
static inline string MethodPropertiesFieldName(const MethodDescriptor *method) {
static inline string MethodPropertiesFieldName(const MethodDescriptor* method) {
return "METHOD_" + ToAllUpperCase(method->name());
}
static inline string MethodPropertiesGetterName(
const MethodDescriptor *method) {
const MethodDescriptor* method) {
return MixedLower("get_" + method->name() + "_method");
}
static inline string MethodIdFieldName(const MethodDescriptor *method) {
static inline string MethodIdFieldName(const MethodDescriptor* method) {
return "METHODID_" + ToAllUpperCase(method->name());
}
static inline string JavaClassName(VARS &vars, const string &name) {
static inline string JavaClassName(VARS& vars, const string& name) {
// string name = google::protobuf::compiler::java::ClassName(desc);
return vars["Package"] + name;
}
static inline string ServiceClassName(const string &service_name) {
static inline string ServiceClassName(const string& service_name) {
return service_name + "Grpc";
}
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
template<typename ITR>
static void GrpcSplitStringToIteratorUsing(const string &full,
const char *delim, ITR &result) {
template <typename ITR>
static void GrpcSplitStringToIteratorUsing(const string& full,
const char* delim, ITR& result) {
// Optimize the common case where delim is a single character.
if (delim[0] != '\0' && delim[1] == '\0') {
char c = delim[0];
const char *p = full.data();
const char *end = p + full.size();
const char* p = full.data();
const char* end = p + full.size();
while (p != end) {
if (*p == c) {
++p;
} else {
const char *start = p;
while (++p != end && *p != c)
;
const char* start = p;
while (++p != end && *p != c);
*result++ = string(start, p - start);
}
}
@@ -157,13 +156,13 @@ static void GrpcSplitStringToIteratorUsing(const string &full,
}
}
static void GrpcSplitStringUsing(const string &full, const char *delim,
std::vector<string> *result) {
static void GrpcSplitStringUsing(const string& full, const char* delim,
std::vector<string>* result) {
std::back_insert_iterator<std::vector<string>> it(*result);
GrpcSplitStringToIteratorUsing(full, delim, it);
}
static std::vector<string> GrpcSplit(const string &full, const char *delim) {
static std::vector<string> GrpcSplit(const string& full, const char* delim) {
std::vector<string> result;
GrpcSplitStringUsing(full, delim, &result);
return result;
@@ -171,7 +170,7 @@ static std::vector<string> GrpcSplit(const string &full, const char *delim) {
// TODO(nmittler): Remove once protobuf includes javadoc methods in
// distribution.
static string GrpcEscapeJavadoc(const string &input) {
static string GrpcEscapeJavadoc(const string& input) {
string result;
result.reserve(input.size() * 2);
@@ -218,7 +217,9 @@ static string GrpcEscapeJavadoc(const string &input) {
// Java interprets Unicode escape sequences anywhere!
result.append("&#92;");
break;
default: result.push_back(c); break;
default:
result.push_back(c);
break;
}
prev = c;
@@ -227,7 +228,7 @@ static string GrpcEscapeJavadoc(const string &input) {
return result;
}
static std::vector<string> GrpcGetDocLines(const string &comments) {
static std::vector<string> GrpcGetDocLines(const string& comments) {
if (!comments.empty()) {
// TODO(kenton): Ideally we should parse the comment text as Markdown and
// write it back as HTML, but this requires a Markdown parser. For now
@@ -238,23 +239,27 @@ static std::vector<string> GrpcGetDocLines(const string &comments) {
string escapedComments = GrpcEscapeJavadoc(comments);
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
return lines;
}
return std::vector<string>();
}
static std::vector<string> GrpcGetDocLinesForDescriptor(
const DescriptorType *descriptor) {
const DescriptorType* descriptor) {
return descriptor->GetAllComments();
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
}
static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
const std::vector<string> &lines,
static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
const std::vector<string>& lines,
bool surroundWithPreTag) {
if (!lines.empty()) {
if (surroundWithPreTag) { printer->Print(" * <pre>\n"); }
if (surroundWithPreTag) {
printer->Print(" * <pre>\n");
}
for (size_t i = 0; i < lines.size(); i++) {
// Most lines should start with a space. Watch out for lines that start
@@ -268,28 +273,30 @@ static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
}
}
if (surroundWithPreTag) { printer->Print(" * </pre>\n"); }
if (surroundWithPreTag) {
printer->Print(" * </pre>\n");
}
}
}
static void GrpcWriteDocComment(Printer *printer, VARS &vars,
const string &comments) {
static void GrpcWriteDocComment(Printer* printer, VARS& vars,
const string& comments) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLines(comments);
GrpcWriteDocCommentBody(printer, vars, lines, false);
printer->Print(" */\n");
}
static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars,
const ServiceDescriptor *service) {
static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars,
const ServiceDescriptor* service) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
GrpcWriteDocCommentBody(printer, vars, lines, true);
printer->Print(" */\n");
}
static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
const MethodDescriptor *method) {
static void GrpcWriteMethodDocComment(Printer* printer, VARS& vars,
const MethodDescriptor* method) {
printer->Print("/**\n");
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
GrpcWriteDocCommentBody(printer, vars, lines, true);
@@ -298,7 +305,7 @@ static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
// outputs static singleton extractor for type stored in "extr_type" and
// "extr_type_name" vars
static void PrintTypeExtractor(Printer *p, VARS &vars) {
static void PrintTypeExtractor(Printer* p, VARS& vars) {
p->Print(vars,
"private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
"extractorOf$extr_type_name$;\n"
@@ -320,8 +327,8 @@ static void PrintTypeExtractor(Printer *p, VARS &vars) {
" }\n"
"}\n\n");
}
static void PrintMethodFields(Printer *p, VARS &vars,
const ServiceDescriptor *service) {
static void PrintMethodFields(Printer* p, VARS& vars,
const ServiceDescriptor* service) {
p->Print("// Static method descriptors that strictly reflect the proto.\n");
vars["service_name"] = service->name();
@@ -443,11 +450,11 @@ enum StubType {
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
const ServiceDescriptor *service);
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
const ServiceDescriptor* service);
// Prints a client interface or implementation class, or a server interface.
static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
StubType type) {
const string service_name = service->name();
vars["service_name"] = service_name;
@@ -493,7 +500,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
vars["client_name"] = client_name;
// Class head
if (!interface) { GrpcWriteServiceDocComment(p, vars, service); }
if (!interface) {
GrpcWriteServiceDocComment(p, vars, service);
}
if (impl_base) {
p->Print(vars,
"public static abstract class $abstract_name$ implements "
@@ -555,7 +564,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
p->Print("\n");
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
// protobuf distro.
if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); }
if (!interface) {
GrpcWriteMethodDocComment(p, vars, &*method);
}
p->Print("public ");
switch (call_type) {
case BLOCKING_CALL:
@@ -620,7 +631,8 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
"responseObserver);\n");
}
break;
default: break;
default:
break;
}
} else if (!interface) {
switch (call_type) {
@@ -695,15 +707,15 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
}
static bool CompareMethodClientStreaming(
const std::unique_ptr<const grpc_generator::Method> &method1,
const std::unique_ptr<const grpc_generator::Method> &method2) {
const std::unique_ptr<const grpc_generator::Method>& method1,
const std::unique_ptr<const grpc_generator::Method>& method2) {
return method1->ClientStreaming() < method2->ClientStreaming();
}
// Place all method invocations into a single class to reduce memory footprint
// on Android.
static void PrintMethodHandlerClass(Printer *p, VARS &vars,
const ServiceDescriptor *service) {
static void PrintMethodHandlerClass(Printer* p, VARS& vars,
const ServiceDescriptor* service) {
// Sort method ids based on ClientStreaming() so switch tables are compact.
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
service->method_count());
@@ -713,7 +725,7 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
stable_sort(sorted_methods.begin(), sorted_methods.end(),
CompareMethodClientStreaming);
for (size_t i = 0; i < sorted_methods.size(); i++) {
auto &method = sorted_methods[i];
auto& method = sorted_methods[i];
vars["method_id"] = to_string(i);
vars["method_id_name"] = MethodIdFieldName(&*method);
p->Print(vars,
@@ -746,7 +758,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
if (method->ClientStreaming() || method->BidiStreaming()) { continue; }
if (method->ClientStreaming() || method->BidiStreaming()) {
continue;
}
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -778,7 +792,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
for (int i = 0; i < service->method_count(); ++i) {
auto method = service->method(i);
if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; }
if (!(method->ClientStreaming() || method->BidiStreaming())) {
continue;
}
vars["method_id_name"] = MethodIdFieldName(&*method);
vars["lower_method_name"] = LowerMethodName(&*method);
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
@@ -803,8 +819,8 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
p->Print("}\n\n");
}
static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
const ServiceDescriptor *service) {
static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
const ServiceDescriptor* service) {
vars["service_name"] = service->name();
// vars["proto_base_descriptor_supplier"] = service->name() +
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
@@ -896,8 +912,8 @@ static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
p->Print("}\n");
}
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
const ServiceDescriptor *service) {
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
const ServiceDescriptor* service) {
vars["service_name"] = service->name();
p->Indent();
p->Print(vars,
@@ -949,8 +965,8 @@ static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
p->Outdent();
}
static void PrintService(Printer *p, VARS &vars,
const ServiceDescriptor *service,
static void PrintService(Printer* p, VARS& vars,
const ServiceDescriptor* service,
bool disable_version) {
vars["service_name"] = service->name();
vars["service_class_name"] = ServiceClassName(service->name());
@@ -1030,7 +1046,7 @@ static void PrintService(Printer *p, VARS &vars,
p->Print("}\n");
}
static void PrintStaticImports(Printer *p) {
static void PrintStaticImports(Printer* p) {
p->Print(
"import java.nio.ByteBuffer;\n"
"import static "
@@ -1063,9 +1079,9 @@ static void PrintStaticImports(Printer *p) {
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
}
static void GenerateService(const grpc_generator::Service *service,
grpc_generator::Printer *printer, VARS &vars,
bool disable_version) {
static void GenerateService(const grpc_generator::Service* service,
grpc_generator::Printer* printer, VARS& vars,
bool disable_version) {
// All non-generated classes must be referred by fully qualified names to
// avoid collision with generated classes.
vars["String"] = "java.lang.String";
@@ -1098,11 +1114,11 @@ static void GenerateService(const grpc_generator::Service *service,
PrintService(printer, vars, service, disable_version);
}
} // namespace
} // namespace
grpc::string GenerateServiceSource(
grpc_generator::File *file, const grpc_generator::Service *service,
grpc_java_generator::Parameters *parameters) {
grpc_generator::File* file, const grpc_generator::Service* service,
grpc_java_generator::Parameters* parameters) {
grpc::string out;
auto printer = file->CreatePrinter(&out);
VARS vars;

View File

@@ -18,6 +18,7 @@
#define NET_GRPC_COMPILER_JAVA_GENERATOR_H_
#include <stdlib.h> // for abort()
#include <iostream>
#include <map>
#include <string>
@@ -39,8 +40,8 @@ class LogHelper {
LogHelper(std::ostream* os) : os_(os) {}
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning( \
disable : 4722) // the flow of control terminates in a destructor
#pragma warning(disable \
: 4722) // the flow of control terminates in a destructor
// (needed to compile ~LogHelper where destructor emits abort intentionally -
// inherited from grpc/java code generator).
#endif

View File

@@ -35,22 +35,22 @@ namespace flatbuffers {
namespace python {
namespace grpc {
namespace {
bool ClientStreaming(const RPCCall *method) {
const Value *val = method->attributes.Lookup("streaming");
bool ClientStreaming(const RPCCall* method) {
const Value* val = method->attributes.Lookup("streaming");
return val != nullptr &&
(val->constant == "client" || val->constant == "bidi");
}
bool ServerStreaming(const RPCCall *method) {
const Value *val = method->attributes.Lookup("streaming");
bool ServerStreaming(const RPCCall* method) {
const Value* val = method->attributes.Lookup("streaming");
return val != nullptr &&
(val->constant == "server" || val->constant == "bidi");
}
void FormatImports(std::stringstream &ss, const Imports &imports) {
void FormatImports(std::stringstream& ss, const Imports& imports) {
std::set<std::string> modules;
std::map<std::string, std::set<std::string>> names_by_module;
for (const Import &import : imports.imports) {
for (const Import& import : imports.imports) {
if (import.IsLocal()) continue; // skip all local imports
if (import.name == "") {
modules.insert(import.module);
@@ -59,14 +59,14 @@ void FormatImports(std::stringstream &ss, const Imports &imports) {
}
}
for (const std::string &module : modules) {
for (const std::string& module : modules) {
ss << "import " << module << '\n';
}
ss << '\n';
for (const auto &import : names_by_module) {
for (const auto& import : names_by_module) {
ss << "from " << import.first << " import ";
size_t i = 0;
for (const std::string &name : import.second) {
for (const std::string& name : import.second) {
if (i > 0) ss << ", ";
ss << name;
++i;
@@ -76,8 +76,8 @@ void FormatImports(std::stringstream &ss, const Imports &imports) {
ss << "\n\n";
}
bool SaveStub(const std::string &filename, const Imports &imports,
const std::string &content) {
bool SaveStub(const std::string& filename, const Imports& imports,
const std::string& content) {
std::stringstream ss;
ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n"
<< '\n'
@@ -90,8 +90,8 @@ bool SaveStub(const std::string &filename, const Imports &imports,
return flatbuffers::SaveFile(filename.c_str(), ss.str(), false);
}
bool SaveService(const std::string &filename, const Imports &imports,
const std::string &content) {
bool SaveService(const std::string& filename, const Imports& imports,
const std::string& content) {
std::stringstream ss;
ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" << '\n';
FormatImports(ss, imports);
@@ -103,32 +103,33 @@ bool SaveService(const std::string &filename, const Imports &imports,
class BaseGenerator {
protected:
BaseGenerator(const Parser &parser, const Namer::Config &config,
const std::string &path, const Version &version)
: parser_{ parser },
namer_{ WithFlagOptions(config, parser.opts, path), Keywords(version) },
version_{ version },
BaseGenerator(const Parser& parser, const Namer::Config& config,
const std::string& path, const Version& version)
: parser_{parser},
namer_{WithFlagOptions(config, parser.opts, path), Keywords(version)},
version_{version},
path_(path) {}
protected:
std::string ModuleForFile(const std::string &file) const {
std::string ModuleForFile(const std::string& file) const {
std::string module = parser_.opts.include_prefix + StripExtension(file) +
parser_.opts.filename_suffix;
std::replace(module.begin(), module.end(), '/', '.');
return module;
}
template<typename T> std::string ModuleFor(const T *def) const {
template <typename T>
std::string ModuleFor(const T* def) const {
if (parser_.opts.one_file) return ModuleForFile(def->file);
return namer_.NamespacedType(*def);
}
std::string NamespaceDir(const Parser &parser, const std::string &path,
const Namespace &ns, const bool dasherize) {
std::string NamespaceDir(const Parser& parser, const std::string& path,
const Namespace& ns, const bool dasherize) {
EnsureDirExists(path);
if (parser.opts.one_file) return path;
std::string namespace_dir = path; // Either empty or ends in separator.
auto &namespaces = ns.components;
auto& namespaces = ns.components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
namespace_dir +=
!dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
@@ -138,32 +139,32 @@ class BaseGenerator {
return namespace_dir;
}
std::string NamespaceDir(const Namespace &ns, const bool dasherize) {
std::string NamespaceDir(const Namespace& ns, const bool dasherize) {
return NamespaceDir(parser_, path_, ns, dasherize);
}
const Parser &parser_;
const Parser& parser_;
const IdlNamer namer_;
const Version version_;
const std::string &path_;
const std::string& path_;
};
class StubGenerator : public BaseGenerator {
public:
StubGenerator(const Parser &parser, const std::string &path,
const Version &version)
StubGenerator(const Parser& parser, const std::string& path,
const Version& version)
: BaseGenerator(parser, kStubConfig, path, version) {}
bool Generate() {
Imports imports;
std::stringstream stub;
std::string ns_name{};
for (const ServiceDef *service : parser_.services_.vec) {
for (const ServiceDef* service : parser_.services_.vec) {
Generate(stub, service, &imports);
ns_name = NamespaceDir(*service->defined_namespace, false);
}
std::string sanitized_suffix{ parser_.opts.grpc_filename_suffix };
std::string sanitized_suffix{parser_.opts.grpc_filename_suffix};
std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_');
std::string filename =
ns_name + kPathSeparator +
@@ -174,14 +175,14 @@ class StubGenerator : public BaseGenerator {
}
private:
void Generate(std::stringstream &ss, const ServiceDef *service,
Imports *imports) {
void Generate(std::stringstream& ss, const ServiceDef* service,
Imports* imports) {
imports->Import("grpc");
ss << "class " << service->name << "Stub(object):\n"
<< " def __init__(self, channel: grpc.Channel) -> None: ...\n";
for (const RPCCall *method : service->calls.vec) {
for (const RPCCall* method : service->calls.vec) {
std::string request = "bytes";
std::string response = "bytes";
@@ -213,7 +214,7 @@ class StubGenerator : public BaseGenerator {
ss << "\n\n";
ss << "class " << service->name << "Servicer(object):\n";
for (const RPCCall *method : service->calls.vec) {
for (const RPCCall* method : service->calls.vec) {
std::string request = "bytes";
std::string response = "bytes";
@@ -252,8 +253,8 @@ class StubGenerator : public BaseGenerator {
class ServiceGenerator : public BaseGenerator {
public:
ServiceGenerator(const Parser &parser, const std::string &path,
const Version &version)
ServiceGenerator(const Parser& parser, const std::string& path,
const Version& version)
: BaseGenerator(parser, kConfig, path, version) {}
bool Generate() {
@@ -274,14 +275,14 @@ class ServiceGenerator : public BaseGenerator {
}
std::string ns_name{};
for (const ServiceDef *service : parser_.services_.vec) {
for (const ServiceDef* service : parser_.services_.vec) {
GenerateStub(ss, service, &imports);
GenerateServicer(ss, service, &imports);
GenerateRegister(ss, service, &imports);
ns_name = NamespaceDir(*service->defined_namespace, false);
}
std::string sanitized_suffix{ parser_.opts.grpc_filename_suffix };
std::string sanitized_suffix{parser_.opts.grpc_filename_suffix};
std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_');
std::string filename =
ns_name + kPathSeparator +
@@ -292,8 +293,8 @@ class ServiceGenerator : public BaseGenerator {
}
private:
void GenerateStub(std::stringstream &ss, const ServiceDef *service,
Imports *imports) {
void GenerateStub(std::stringstream& ss, const ServiceDef* service,
Imports* imports) {
ss << "class " << service->name << "Stub";
if (version_.major != 3) ss << "(object)";
ss << ":\n"
@@ -307,7 +308,7 @@ class ServiceGenerator : public BaseGenerator {
<< " '''\n"
<< '\n';
for (const RPCCall *method : service->calls.vec) {
for (const RPCCall* method : service->calls.vec) {
std::string response = namer_.Type(*method->response);
imports->Import(ModuleFor(method->response), response);
@@ -330,8 +331,8 @@ class ServiceGenerator : public BaseGenerator {
ss << '\n';
}
void GenerateServicer(std::stringstream &ss, const ServiceDef *service,
Imports *imports) {
void GenerateServicer(std::stringstream& ss, const ServiceDef* service,
Imports* imports) {
imports->Import("grpc");
ss << "class " << service->name << "Servicer";
@@ -340,7 +341,7 @@ class ServiceGenerator : public BaseGenerator {
<< " '''Interface exported by the server.'''\n"
<< '\n';
for (const RPCCall *method : service->calls.vec) {
for (const RPCCall* method : service->calls.vec) {
const std::string request_param =
ClientStreaming(method) ? "request_iterator" : "request";
ss << " def " << method->name << "(self, " << request_param
@@ -354,15 +355,15 @@ class ServiceGenerator : public BaseGenerator {
ss << '\n';
}
void GenerateRegister(std::stringstream &ss, const ServiceDef *service,
Imports *imports) {
void GenerateRegister(std::stringstream& ss, const ServiceDef* service,
Imports* imports) {
imports->Import("grpc");
ss << "def add_" << service->name
<< "Servicer_to_server(servicer, server):\n"
<< " rpc_method_handlers = {\n";
for (const RPCCall *method : service->calls.vec) {
for (const RPCCall* method : service->calls.vec) {
std::string request = namer_.Type(*method->request);
imports->Import(ModuleFor(method->request), request);
@@ -393,15 +394,15 @@ class ServiceGenerator : public BaseGenerator {
};
} // namespace
bool Generate(const Parser &parser, const std::string &path,
const Version &version) {
ServiceGenerator generator{ parser, path, version };
bool Generate(const Parser& parser, const std::string& path,
const Version& version) {
ServiceGenerator generator{parser, path, version};
return generator.Generate();
}
bool GenerateStub(const Parser &parser, const std::string &path,
const Version &version) {
StubGenerator generator{ parser, path, version };
bool GenerateStub(const Parser& parser, const std::string& path,
const Version& version) {
StubGenerator generator{parser, path, version};
return generator.Generate();
}

View File

@@ -27,11 +27,11 @@
namespace flatbuffers {
namespace python {
namespace grpc {
bool Generate(const Parser &parser, const std::string &path,
const Version &version);
bool Generate(const Parser& parser, const std::string& path,
const Version& version);
bool GenerateStub(const Parser &parser, const std::string &path,
const Version &version);
bool GenerateStub(const Parser& parser, const std::string& path,
const Version& version);
} // namespace grpc
} // namespace python
} // namespace flatbuffers

View File

@@ -20,34 +20,35 @@
* please open an issue in the flatbuffers repository. This file should always
* be maintained according to the Swift-grpc repository
*/
#include "src/compiler/swift_generator.h"
#include <map>
#include <sstream>
#include "flatbuffers/util.h"
#include "src/compiler/schema_interface.h"
#include "src/compiler/swift_generator.h"
namespace grpc_swift_generator {
namespace {
static std::string WrapInNameSpace(const std::vector<std::string> &components,
const grpc::string &name) {
static std::string WrapInNameSpace(const std::vector<std::string>& components,
const grpc::string& name) {
std::string qualified_name;
for (auto it = components.begin(); it != components.end(); ++it)
qualified_name += *it + "_";
return qualified_name + name;
}
static grpc::string GenerateMessage(const std::vector<std::string> &components,
const grpc::string &name) {
static grpc::string GenerateMessage(const std::vector<std::string>& components,
const grpc::string& name) {
return "Message<" + WrapInNameSpace(components, name) + ">";
}
// MARK: - Client
static void GenerateClientFuncName(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateClientFuncName(
const grpc_generator::Method* method, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
if (method->NoStreaming()) {
printer->Print(vars,
@@ -83,9 +84,9 @@ static void GenerateClientFuncName(const grpc_generator::Method *method,
" ) -> BidirectionalStreamingCall<$Input$, $Output$>");
}
static void GenerateClientFuncBody(const grpc_generator::Method *method,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateClientFuncBody(
const grpc_generator::Method* method, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
vars["Interceptor"] =
"interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []";
@@ -133,9 +134,9 @@ static void GenerateClientFuncBody(const grpc_generator::Method *method,
" )\n");
}
void GenerateClientProtocol(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
void GenerateClientProtocol(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(
vars,
@@ -207,8 +208,8 @@ void GenerateClientProtocol(const grpc_generator::Service *service,
printer->Print("}\n\n");
}
void GenerateClientClass(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
void GenerateClientClass(grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars,
"$ACCESS$ final class $ServiceQualifiedName$ServiceClient: "
@@ -237,7 +238,7 @@ void GenerateClientClass(grpc_generator::Printer *printer,
// MARK: - Server
grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
grpc::string GenerateServerFuncName(const grpc_generator::Method* method) {
if (method->NoStreaming()) {
return "func $MethodName$(request: $Input$"
", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>";
@@ -258,7 +259,7 @@ grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
"-> EventLoopFuture<(StreamEvent<$Input$>) -> Void>";
}
grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
grpc::string GenerateServerExtensionBody(const grpc_generator::Method* method) {
grpc::string start = " case \"$MethodName$\":\n ";
grpc::string interceptors =
" interceptors: self.interceptors?.make$MethodName$Interceptors() "
@@ -302,9 +303,9 @@ grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
return "";
}
void GenerateServerProtocol(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
void GenerateServerProtocol(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars,
"$ACCESS$ protocol $ServiceQualifiedName$Provider: "
@@ -373,14 +374,16 @@ void GenerateServerProtocol(const grpc_generator::Service *service,
}
printer->Print("}");
}
} // namespace
} // namespace
grpc::string Generate(grpc_generator::File *file,
const grpc_generator::Service *service) {
grpc::string Generate(grpc_generator::File* file,
const grpc_generator::Service* service) {
grpc::string output;
std::map<grpc::string, grpc::string> vars;
vars["PATH"] = file->package();
if (!file->package().empty()) { vars["PATH"].append("."); }
if (!file->package().empty()) {
vars["PATH"].append(".");
}
vars["ServiceQualifiedName"] =
WrapInNameSpace(service->namespace_parts(), service->name());
vars["ServiceName"] = service->name();

View File

@@ -20,8 +20,8 @@
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
#include <string>
#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
@@ -31,7 +31,7 @@ typedef GRPC_CUSTOM_STRING string;
} // namespace grpc
namespace grpc_swift_generator {
grpc::string Generate(grpc_generator::File *file,
const grpc_generator::Service *service);
grpc::string Generate(grpc_generator::File* file,
const grpc_generator::Service* service);
grpc::string GenerateHeader();
} // namespace grpc_swift_generator

View File

@@ -33,8 +33,8 @@ namespace grpc_ts_generator {
namespace {
static grpc::string GenerateNamespace(const std::vector<std::string> ns,
const std::string filename,
const bool include_separator) {
const std::string filename,
const bool include_separator) {
grpc::string path = "";
if (include_separator) path += ".";
@@ -56,10 +56,10 @@ static grpc::string GenerateNamespace(const std::vector<std::string> ns,
// MARK: - Shared code
static void GenerateImports(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary,
const bool grpc_var_import) {
static void GenerateImports(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary,
const bool grpc_var_import) {
auto vars = *dictonary;
printer->Print(
"// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n");
@@ -105,9 +105,9 @@ static void GenerateImports(const grpc_generator::Service *service,
// MARK: - Generate Main GRPC Code
static void GetStreamType(grpc_generator::Printer *printer,
const grpc_generator::Method *method,
std::map<grpc::string, grpc::string> *dictonary) {
static void GetStreamType(grpc_generator::Printer* printer,
const grpc_generator::Method* method,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
auto client_streaming = method->ClientStreaming() || method->BidiStreaming();
auto server_streaming = method->ServerStreaming() || method->BidiStreaming();
@@ -117,8 +117,9 @@ static void GetStreamType(grpc_generator::Printer *printer,
printer->Print(vars, "responseStream: $ServerStreaming$,\n");
}
static void GenerateSerializeMethod(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateSerializeMethod(
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
printer->Indent();
@@ -134,8 +135,8 @@ static void GenerateSerializeMethod(grpc_generator::Printer *printer,
}
static void GenerateDeserializeMethod(
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars, "function deserialize_$Type$(buffer) {\n");
printer->Indent();
@@ -146,9 +147,9 @@ static void GenerateDeserializeMethod(
printer->Print("}\n\n");
}
static void GenerateMethods(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateMethods(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
std::set<grpc::string> generated_functions;
@@ -178,9 +179,9 @@ static void GenerateMethods(const grpc_generator::Service *service,
}
}
static void GenerateService(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateService(const grpc_generator::Service* service,
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
vars["NAME"] = service->name() + "Service";
@@ -213,17 +214,19 @@ static void GenerateService(const grpc_generator::Service *service,
"grpc.makeGenericClientConstructor($NAME$);");
}
} // namespace
} // namespace
grpc::string Generate(grpc_generator::File *file,
const grpc_generator::Service *service,
const grpc::string &filename) {
grpc::string Generate(grpc_generator::File* file,
const grpc_generator::Service* service,
const grpc::string& filename) {
grpc::string output;
std::map<grpc::string, grpc::string> vars;
vars["PATH"] = file->package();
if (!file->package().empty()) { vars["PATH"].append("."); }
if (!file->package().empty()) {
vars["PATH"].append(".");
}
vars["ServiceName"] = service->name();
vars["FBSFile"] = service->name() + "_fbs";
@@ -240,8 +243,8 @@ namespace {
// MARK: - Generate Interface
static void FillInterface(grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void FillInterface(grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars,
"interface I$ServiceName$Service_I$MethodName$ extends "
@@ -258,9 +261,9 @@ static void FillInterface(grpc_generator::Printer *printer,
printer->Print("}\n");
}
static void GenerateInterfaces(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateInterfaces(
const grpc_generator::Service* service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it);
@@ -281,8 +284,8 @@ static void GenerateInterfaces(const grpc_generator::Service *service,
}
static void GenerateExportedInterface(
const grpc_generator::Service *service, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
const grpc_generator::Service* service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars,
"export interface I$ServiceName$Server extends "
@@ -324,9 +327,9 @@ static void GenerateExportedInterface(
printer->Print("}\n");
}
static void GenerateMainInterface(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateMainInterface(
const grpc_generator::Service* service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(
vars,
@@ -351,11 +354,13 @@ static void GenerateMainInterface(const grpc_generator::Service *service,
static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; }
static grpc::string GenerateOptions() { return "options: Partial<grpc.CallOptions>"; }
static grpc::string GenerateOptions() {
return "options: Partial<grpc.CallOptions>";
}
static void GenerateUnaryClientInterface(
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
grpc::string callback =
@@ -369,8 +374,8 @@ static void GenerateUnaryClientInterface(
}
static void GenerateClientWriteStreamInterface(
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string callback =
@@ -386,8 +391,8 @@ static void GenerateClientWriteStreamInterface(
}
static void GenerateClientReadableStreamInterface(
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n";
@@ -398,8 +403,8 @@ static void GenerateClientReadableStreamInterface(
}
static void GenerateDepluxStreamInterface(
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
grpc::string main = "$ISPUBLIC$$MethodName$(";
grpc::string end_function =
@@ -413,9 +418,9 @@ static void GenerateDepluxStreamInterface(
.c_str());
}
static void GenerateClientInterface(const grpc_generator::Service *service,
grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
static void GenerateClientInterface(
const grpc_generator::Service* service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars, "export interface I$ServiceName$Client {\n");
printer->Indent();
@@ -452,8 +457,8 @@ static void GenerateClientInterface(const grpc_generator::Service *service,
}
static void GenerateClientClassInterface(
const grpc_generator::Service *service, grpc_generator::Printer *printer,
std::map<grpc::string, grpc::string> *dictonary) {
const grpc_generator::Service* service, grpc_generator::Printer* printer,
std::map<grpc::string, grpc::string>* dictonary) {
auto vars = *dictonary;
printer->Print(vars,
"export class $ServiceName$Client extends grpc.Client "
@@ -492,12 +497,11 @@ static void GenerateClientClassInterface(
printer->Outdent();
printer->Print("}\n");
}
} // namespace
} // namespace
grpc::string GenerateInterface(grpc_generator::File *file,
const grpc_generator::Service *service,
const grpc::string &filename) {
grpc::string GenerateInterface(grpc_generator::File* file,
const grpc_generator::Service* service,
const grpc::string& filename) {
grpc::string output;
std::set<grpc::string> generated_functions;
@@ -505,7 +509,9 @@ grpc::string GenerateInterface(grpc_generator::File *file,
vars["PATH"] = file->package();
if (!file->package().empty()) { vars["PATH"].append("."); }
if (!file->package().empty()) {
vars["PATH"].append(".");
}
vars["ServiceName"] = service->name();
vars["FBSFile"] = service->name() + "_fbs";

View File

@@ -5,8 +5,8 @@
#include "src/compiler/schema_interface.h"
#ifndef GRPC_CUSTOM_STRING
# include <string>
# define GRPC_CUSTOM_STRING std::string
#include <string>
#define GRPC_CUSTOM_STRING std::string
#endif
namespace grpc {
@@ -16,11 +16,11 @@ typedef GRPC_CUSTOM_STRING string;
} // namespace grpc
namespace grpc_ts_generator {
grpc::string Generate(grpc_generator::File *file,
const grpc_generator::Service *service,
const grpc::string &filename);
grpc::string Generate(grpc_generator::File* file,
const grpc_generator::Service* service,
const grpc::string& filename);
grpc::string GenerateInterface(grpc_generator::File *file,
const grpc_generator::Service *service,
const grpc::string &filename);
grpc::string GenerateInterface(grpc_generator::File* file,
const grpc_generator::Service* service,
const grpc::string& filename);
} // namespace grpc_ts_generator

View File

@@ -1,10 +1,11 @@
import java.nio.ByteBuffer;
import MyGame.Example.Monster;
import MyGame.Example.Stat;
import com.google.flatbuffers.FlatBufferBuilder;
import java.nio.ByteBuffer;
class GameFactory {
public static Monster createMonster(String monsterName, short nestedMonsterHp, short nestedMonsterMana) {
public static Monster createMonster(
String monsterName, short nestedMonsterHp, short nestedMonsterMana) {
FlatBufferBuilder builder = new FlatBufferBuilder();
int name_offset = builder.createString(monsterName);
@@ -31,12 +32,11 @@ class GameFactory {
return monster;
}
public static Stat createStat(String greeting, long val, int count) {
public static Stat createStat(String greeting, long val, int count) {
FlatBufferBuilder builder = new FlatBufferBuilder();
int statOffset = Stat.createStat(builder, builder.createString(greeting), val, count);
builder.finish(statOffset);
Stat stat = Stat.getRootAsStat(builder.dataBuffer());
return stat;
}
}

View File

@@ -17,226 +17,236 @@
import MyGame.Example.Monster;
import MyGame.Example.MonsterStorageGrpc;
import MyGame.Example.Stat;
import com.google.flatbuffers.FlatBufferBuilder;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Assert;
import java.io.IOException;
import java.lang.InterruptedException;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CountDownLatch;
/**
* Demonstrates basic client-server interaction using grpc-java over netty.
*/
/** Demonstrates basic client-server interaction using grpc-java over netty. */
public class JavaGrpcTest {
static final String BIG_MONSTER_NAME = "Cyberdemon";
static final short nestedMonsterHp = 600;
static final short nestedMonsterMana = 1024;
static final int numStreamedMsgs = 10;
static final int timeoutMs = 3000;
static Server server;
static ManagedChannel channel;
static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub;
static MonsterStorageGrpc.MonsterStorageStub asyncStub;
static final String BIG_MONSTER_NAME = "Cyberdemon";
static final short nestedMonsterHp = 600;
static final short nestedMonsterMana = 1024;
static final int numStreamedMsgs = 10;
static final int timeoutMs = 3000;
static Server server;
static ManagedChannel channel;
static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub;
static MonsterStorageGrpc.MonsterStorageStub asyncStub;
static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase {
@Override
public void store(Monster request, io.grpc.stub.StreamObserver<Stat> responseObserver) {
Assert.assertEquals(request.name(), BIG_MONSTER_NAME);
Assert.assertEquals(request.hp(), nestedMonsterHp);
Assert.assertEquals(request.mana(), nestedMonsterMana);
System.out.println("Received store request from " + request.name());
// Create a response from the incoming request name.
Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10);
responseObserver.onNext(stat);
responseObserver.onCompleted();
}
@Override
public void retrieve(Stat request, io.grpc.stub.StreamObserver<Monster> responseObserver) {
// Create 10 monsters for streaming response.
for (int i=0; i<numStreamedMsgs; i++) {
Monster monster = GameFactory.createMonsterFromStat(request, i);
responseObserver.onNext(monster);
}
responseObserver.onCompleted();
}
@Override
public StreamObserver<Monster> getMaxHitPoint(final StreamObserver<Stat> responseObserver) {
return computeMinMax(responseObserver, false);
}
@Override
public StreamObserver<Monster> getMinMaxHitPoints(final StreamObserver<Stat> responseObserver) {
return computeMinMax(responseObserver, true);
}
private StreamObserver<Monster> computeMinMax(final StreamObserver<Stat> responseObserver, final boolean includeMin) {
final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE);
final AtomicReference<String> maxHpMonsterName = new AtomicReference<String>();
final AtomicInteger maxHpCount = new AtomicInteger();
final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE);
final AtomicReference<String> minHpMonsterName = new AtomicReference<String>();
final AtomicInteger minHpCount = new AtomicInteger();
return new StreamObserver<Monster>() {
public void onNext(Monster monster) {
if (monster.hp() > maxHp.get()) {
// Found a monster of higher hit points.
maxHp.set(monster.hp());
maxHpMonsterName.set(monster.name());
maxHpCount.set(1);
}
else if (monster.hp() == maxHp.get()) {
// Count how many times we saw a monster of current max hit points.
maxHpCount.getAndIncrement();
}
if (monster.hp() < minHp.get()) {
// Found a monster of a lower hit points.
minHp.set(monster.hp());
minHpMonsterName.set(monster.name());
minHpCount.set(1);
}
else if (monster.hp() == minHp.get()) {
// Count how many times we saw a monster of current min hit points.
minHpCount.getAndIncrement();
}
}
public void onCompleted() {
Stat maxHpStat = GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get());
// Send max hit points first.
responseObserver.onNext(maxHpStat);
if (includeMin) {
// Send min hit points.
Stat minHpStat = GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get());
responseObserver.onNext(minHpStat);
}
responseObserver.onCompleted();
}
public void onError(Throwable t) {
// Not expected
Assert.fail();
};
};
}
static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase {
@Override
public void store(Monster request, io.grpc.stub.StreamObserver<Stat> responseObserver) {
Assert.assertEquals(request.name(), BIG_MONSTER_NAME);
Assert.assertEquals(request.hp(), nestedMonsterHp);
Assert.assertEquals(request.mana(), nestedMonsterMana);
System.out.println("Received store request from " + request.name());
// Create a response from the incoming request name.
Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10);
responseObserver.onNext(stat);
responseObserver.onCompleted();
}
@org.junit.BeforeClass
public static void startServer() throws IOException {
server = ServerBuilder.forPort(0).addService(new MyService()).build().start();
int port = server.getPort();
channel = ManagedChannelBuilder.forAddress("localhost", port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.directExecutor()
.build();
blockingStub = MonsterStorageGrpc.newBlockingStub(channel);
asyncStub = MonsterStorageGrpc.newStub(channel);
}
@org.junit.Test
public void testUnary() throws IOException {
Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
Stat stat = blockingStub.store(monsterRequest);
Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME);
System.out.println("Received stat response from service: " + stat.id());
}
@org.junit.Test
public void testServerStreaming() throws IOException {
Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
Stat stat = blockingStub.store(monsterRequest);
Iterator<Monster> iterator = blockingStub.retrieve(stat);
int counter = 0;
while(iterator.hasNext()) {
Monster m = iterator.next();
System.out.println("Received monster " + m.name());
counter ++;
}
Assert.assertEquals(counter, numStreamedMsgs);
System.out.println("FlatBuffers GRPC client/server test: completed successfully");
}
@org.junit.Test
public void testClientStreaming() throws IOException, InterruptedException {
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
final CountDownLatch streamAlive = new CountDownLatch(1);
StreamObserver<Stat> statObserver = new StreamObserver<Stat>() {
public void onCompleted() {
streamAlive.countDown();
}
public void onError(Throwable ex) { }
public void onNext(Stat stat) {
maxHitStat.set(stat);
}
};
StreamObserver<Monster> monsterStream = asyncStub.getMaxHitPoint(statObserver);
short count = 10;
for (short i = 0;i < count; ++i) {
Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
monsterStream.onNext(monster);
@Override
public void retrieve(Stat request, io.grpc.stub.StreamObserver<Monster> responseObserver) {
// Create 10 monsters for streaming response.
for (int i = 0; i < numStreamedMsgs; i++) {
Monster monster = GameFactory.createMonsterFromStat(request, i);
responseObserver.onNext(monster);
}
monsterStream.onCompleted();
// Wait a little bit for the server to send the stats of the monster with the max hit-points.
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
Assert.assertEquals(maxHitStat.get().count(), 1);
responseObserver.onCompleted();
}
@org.junit.Test
public void testBiDiStreaming() throws IOException, InterruptedException {
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
final AtomicReference<Stat> minHitStat = new AtomicReference<Stat>();
final CountDownLatch streamAlive = new CountDownLatch(1);
@Override
public StreamObserver<Monster> getMaxHitPoint(final StreamObserver<Stat> responseObserver) {
return computeMinMax(responseObserver, false);
}
StreamObserver<Stat> statObserver = new StreamObserver<Stat>() {
public void onCompleted() {
streamAlive.countDown();
@Override
public StreamObserver<Monster> getMinMaxHitPoints(final StreamObserver<Stat> responseObserver) {
return computeMinMax(responseObserver, true);
}
private StreamObserver<Monster> computeMinMax(
final StreamObserver<Stat> responseObserver, final boolean includeMin) {
final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE);
final AtomicReference<String> maxHpMonsterName = new AtomicReference<String>();
final AtomicInteger maxHpCount = new AtomicInteger();
final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE);
final AtomicReference<String> minHpMonsterName = new AtomicReference<String>();
final AtomicInteger minHpCount = new AtomicInteger();
return new StreamObserver<Monster>() {
public void onNext(Monster monster) {
if (monster.hp() > maxHp.get()) {
// Found a monster of higher hit points.
maxHp.set(monster.hp());
maxHpMonsterName.set(monster.name());
maxHpCount.set(1);
} else if (monster.hp() == maxHp.get()) {
// Count how many times we saw a monster of current max hit points.
maxHpCount.getAndIncrement();
}
if (monster.hp() < minHp.get()) {
// Found a monster of a lower hit points.
minHp.set(monster.hp());
minHpMonsterName.set(monster.name());
minHpCount.set(1);
} else if (monster.hp() == minHp.get()) {
// Count how many times we saw a monster of current min hit points.
minHpCount.getAndIncrement();
}
}
public void onError(Throwable ex) { }
public void onNext(Stat stat) {
// We expect the server to send the max stat first and then the min stat.
if (maxHitStat.get() == null) {
public void onCompleted() {
Stat maxHpStat =
GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get());
// Send max hit points first.
responseObserver.onNext(maxHpStat);
if (includeMin) {
// Send min hit points.
Stat minHpStat =
GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get());
responseObserver.onNext(minHpStat);
}
responseObserver.onCompleted();
}
public void onError(Throwable t) {
// Not expected
Assert.fail();
}
;
};
}
}
@org.junit.BeforeClass
public static void startServer() throws IOException {
server = ServerBuilder.forPort(0).addService(new MyService()).build().start();
int port = server.getPort();
channel =
ManagedChannelBuilder.forAddress("localhost", port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.directExecutor()
.build();
blockingStub = MonsterStorageGrpc.newBlockingStub(channel);
asyncStub = MonsterStorageGrpc.newStub(channel);
}
@org.junit.Test
public void testUnary() throws IOException {
Monster monsterRequest =
GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
Stat stat = blockingStub.store(monsterRequest);
Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME);
System.out.println("Received stat response from service: " + stat.id());
}
@org.junit.Test
public void testServerStreaming() throws IOException {
Monster monsterRequest =
GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
Stat stat = blockingStub.store(monsterRequest);
Iterator<Monster> iterator = blockingStub.retrieve(stat);
int counter = 0;
while (iterator.hasNext()) {
Monster m = iterator.next();
System.out.println("Received monster " + m.name());
counter++;
}
Assert.assertEquals(counter, numStreamedMsgs);
System.out.println("FlatBuffers GRPC client/server test: completed successfully");
}
@org.junit.Test
public void testClientStreaming() throws IOException, InterruptedException {
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
final CountDownLatch streamAlive = new CountDownLatch(1);
StreamObserver<Stat> statObserver =
new StreamObserver<Stat>() {
public void onCompleted() {
streamAlive.countDown();
}
public void onError(Throwable ex) {}
public void onNext(Stat stat) {
maxHitStat.set(stat);
}
else {
minHitStat.set(stat);
}
}
};
StreamObserver<Monster> monsterStream = asyncStub.getMinMaxHitPoints(statObserver);
short count = 10;
for (short i = 0;i < count; ++i) {
Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
monsterStream.onNext(monster);
}
monsterStream.onCompleted();
// Wait a little bit for the server to send the stats of the monster with the max and min hit-points.
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
Assert.assertEquals(maxHitStat.get().count(), 1);
Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0);
Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0);
Assert.assertEquals(minHitStat.get().count(), 1);
};
StreamObserver<Monster> monsterStream = asyncStub.getMaxHitPoint(statObserver);
short count = 10;
for (short i = 0; i < count; ++i) {
Monster monster =
GameFactory.createMonster(
BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
monsterStream.onNext(monster);
}
monsterStream.onCompleted();
// Wait a little bit for the server to send the stats of the monster with the max hit-points.
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
Assert.assertEquals(maxHitStat.get().count(), 1);
}
@org.junit.Test
public void testBiDiStreaming() throws IOException, InterruptedException {
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
final AtomicReference<Stat> minHitStat = new AtomicReference<Stat>();
final CountDownLatch streamAlive = new CountDownLatch(1);
StreamObserver<Stat> statObserver =
new StreamObserver<Stat>() {
public void onCompleted() {
streamAlive.countDown();
}
public void onError(Throwable ex) {}
public void onNext(Stat stat) {
// We expect the server to send the max stat first and then the min stat.
if (maxHitStat.get() == null) {
maxHitStat.set(stat);
} else {
minHitStat.set(stat);
}
}
};
StreamObserver<Monster> monsterStream = asyncStub.getMinMaxHitPoints(statObserver);
short count = 10;
for (short i = 0; i < count; ++i) {
Monster monster =
GameFactory.createMonster(
BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
monsterStream.onNext(monster);
}
monsterStream.onCompleted();
// Wait a little bit for the server to send the stats of the monster with the max and min
// hit-points.
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
Assert.assertEquals(maxHitStat.get().count(), 1);
Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0);
Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0);
Assert.assertEquals(minHitStat.get().count(), 1);
}
}

View File

@@ -1,13 +1,13 @@
from __future__ import print_function
from concurrent import futures
import os
import sys
import grpc
import flatbuffers
import grpc
from concurrent import futures
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'tests'))
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "tests"))
import MyGame.Example.Monster as Monster
import MyGame.Example.Stat as Stat
import MyGame.Example.Vec3 as Vec3
@@ -39,136 +39,138 @@ test_no_of_monsters = 2
class MonsterStorage(monster_grpc_fb.MonsterStorageServicer):
def Store(self, request, context):
def Store(self, request, context):
m = Monster.Monster().GetRootAsMonster(request, 0)
m = Monster.Monster().GetRootAsMonster(request, 0)
assert m.Name().decode("utf-8") == test_monster_name1
assert m.Name().decode("utf-8") == test_monster_name1
assert m.Pos().X() == test_X
assert m.Pos().Y() == test_Y
assert m.Pos().Z() == test_Z
assert m.Pos().Test1() == test_test1
assert m.Pos().Test2() == test_color
test3 = Test.Test()
assert m.Pos().Test3(test3).A() == test_a
assert m.Pos().Test3(test3).B() == test_b
assert m.Pos().X() == test_X
assert m.Pos().Y() == test_Y
assert m.Pos().Z() == test_Z
assert m.Pos().Test1() == test_test1
assert m.Pos().Test2() == test_color
test3 = Test.Test()
assert m.Pos().Test3(test3).A() == test_a
assert m.Pos().Test3(test3).B() == test_b
assert m.Hp() == test_hp
assert m.Hp() == test_hp
assert m.Color() == test_color
assert m.Color() == test_color
assert m.InventoryLength() == len(test_inventory)
for i in range(0, len(test_inventory)):
assert m.Inventory(i) == test_inventory[len(test_inventory)-i -1]
assert m.InventoryLength() == len(test_inventory)
for i in range(0, len(test_inventory)):
assert m.Inventory(i) == test_inventory[len(test_inventory) - i - 1]
assert m.TestType() == test_testtype
assert m.TestType() == test_testtype
assert m.Test() is not None
table = m.Test()
assert m.Test() is not None
table = m.Test()
m2 = Monster.Monster()
m2.Init(table.Bytes, table.Pos)
assert m2.Name().decode("utf-8") == test_monster_name2
m2 = Monster.Monster()
m2.Init(table.Bytes, table.Pos)
assert m2.Name().decode("utf-8") == test_monster_name2
m3 = m.Enemy()
assert m3.Name().decode("utf-8") == test_monster_name2
m3 = m.Enemy()
assert m3.Name().decode("utf-8") == test_monster_name2
assert m.Testarrayofstring(0).decode("utf-8") == test_string
assert m.Testarrayofstring(0).decode("utf-8") == test_string
b = flatbuffers.Builder(0)
i = b.CreateString(test_stat_id)
Stat.StatStart(b)
Stat.StatAddId(b, i)
Stat.StatAddVal(b, test_stat_val)
Stat.StatAddCount(b, test_stat_count)
b.Finish(Stat.StatEnd(b))
return bytes(b.Output())
b = flatbuffers.Builder(0)
i = b.CreateString(test_stat_id)
Stat.StatStart(b)
Stat.StatAddId(b, i)
Stat.StatAddVal(b, test_stat_val)
Stat.StatAddCount(b, test_stat_count)
b.Finish(Stat.StatEnd(b))
return bytes(b.Output())
def Retrieve(self, request, context):
def Retrieve(self, request, context):
s = Stat.Stat().GetRootAsStat(request, 0)
s = Stat.Stat().GetRootAsStat(request, 0)
no_of_monsters = test_no_of_monsters
for i in range(0, no_of_monsters):
b = flatbuffers.Builder(0)
i = b.CreateString(test_monsters_name_retrieve[i])
Monster.MonsterStart(b)
Monster.MonsterAddName(b, i)
b.Finish(Monster.MonsterEnd(b))
yield bytes(b.Output())
no_of_monsters = test_no_of_monsters
for i in range(0, no_of_monsters):
b = flatbuffers.Builder(0)
i = b.CreateString(test_monsters_name_retrieve[i])
Monster.MonsterStart(b)
Monster.MonsterAddName(b, i)
b.Finish(Monster.MonsterEnd(b))
yield bytes(b.Output())
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server)
server.add_insecure_port('[::]:50051')
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.start()
run()
run()
def run():
channel = grpc.insecure_channel('127.0.0.1:50051')
stub = monster_grpc_fb.MonsterStorageStub(channel)
channel = grpc.insecure_channel("127.0.0.1:50051")
stub = monster_grpc_fb.MonsterStorageStub(channel)
b = flatbuffers.Builder(0)
name2 = b.CreateString(test_monster_name2)
name1 = b.CreateString(test_monster_name1)
Monster.MonsterStart(b)
Monster.MonsterAddName(b, name2)
monster2 = Monster.MonsterEnd(b)
test1 = b.CreateString(test_string)
b = flatbuffers.Builder(0)
name2 = b.CreateString(test_monster_name2)
name1 = b.CreateString(test_monster_name1)
Monster.MonsterStart(b)
Monster.MonsterAddName(b, name2)
monster2 = Monster.MonsterEnd(b)
test1 = b.CreateString(test_string)
Monster.MonsterStartInventoryVector(b, len(test_inventory))
for i in range(0, len(test_inventory)):
b.PrependByte(test_inventory[i])
inv = b.EndVector()
Monster.MonsterStartInventoryVector(b, len(test_inventory))
for i in range(0, len(test_inventory)):
b.PrependByte(test_inventory[i])
inv = b.EndVector()
Monster.MonsterStartTest4Vector(b, 2)
Test.CreateTest(b, 10, 20)
Test.CreateTest(b, 30, 40)
test4 = b.EndVector()
Monster.MonsterStartTest4Vector(b, 2)
Test.CreateTest(b, 10, 20)
Test.CreateTest(b, 30, 40)
test4 = b.EndVector()
Monster.MonsterStartTestarrayofstringVector(b, 1)
b.PrependUOffsetTRelative(test1)
test_array_of_string = b.EndVector()
Monster.MonsterStartTestarrayofstringVector(b, 1)
b.PrependUOffsetTRelative(test1)
test_array_of_string = b.EndVector()
Monster.MonsterStart(b)
Monster.MonsterStart(b)
Monster.MonsterAddHp(b, test_hp)
Monster.MonsterAddName(b, name1)
Monster.MonsterAddColor(b, test_color)
pos = Vec3.CreateVec3(b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b)
Monster.MonsterAddPos(b, pos)
Monster.MonsterAddInventory(b, inv)
Monster.MonsterAddTestType(b, test_testtype)
Monster.MonsterAddTest(b, monster2)
Monster.MonsterAddTest4(b, test4)
Monster.MonsterAddEnemy(b, monster2)
Monster.MonsterAddTestarrayofstring(b, test_array_of_string)
monster = Monster.MonsterEnd(b)
Monster.MonsterAddHp(b, test_hp)
Monster.MonsterAddName(b, name1)
Monster.MonsterAddColor(b, test_color)
pos = Vec3.CreateVec3(
b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b
)
Monster.MonsterAddPos(b, pos)
Monster.MonsterAddInventory(b, inv)
Monster.MonsterAddTestType(b, test_testtype)
Monster.MonsterAddTest(b, monster2)
Monster.MonsterAddTest4(b, test4)
Monster.MonsterAddEnemy(b, monster2)
Monster.MonsterAddTestarrayofstring(b, test_array_of_string)
monster = Monster.MonsterEnd(b)
b.Finish(monster)
b.Finish(monster)
stat_response = stub.Store(bytes(b.Output()))
stat_response = stub.Store(bytes(b.Output()))
s = Stat.Stat().GetRootAsStat(stat_response, 0)
s = Stat.Stat().GetRootAsStat(stat_response, 0)
assert s.Id().decode("utf-8") == test_stat_id
assert s.Val() == test_stat_val
assert s.Count() == test_stat_count
assert s.Id().decode("utf-8") == test_stat_id
assert s.Val() == test_stat_val
assert s.Count() == test_stat_count
monster_reponses = stub.Retrieve(stat_response)
count = 0
for monster_reponse in monster_reponses:
m = Monster.Monster().GetRootAsMonster(monster_reponse, 0)
assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count]
count = count + 1
monster_reponses = stub.Retrieve(stat_response)
count = 0
for monster_reponse in monster_reponses:
m = Monster.Monster().GetRootAsMonster(monster_reponse, 0)
assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count]
count = count + 1
if __name__ == '__main__':
serve()
if __name__ == "__main__":
serve()

View File

@@ -25,69 +25,69 @@ class IdlNamer : public Namer {
using Namer::Variable;
using Namer::Variant;
std::string Constant(const FieldDef &d) const { return Constant(d.name); }
std::string Constant(const FieldDef& d) const { return Constant(d.name); }
// Types are always structs or enums so we can only expose these two
// overloads.
std::string Type(const StructDef &d) const { return Type(d.name); }
std::string Type(const EnumDef &d) const { return Type(d.name); }
std::string Type(const StructDef& d) const { return Type(d.name); }
std::string Type(const EnumDef& d) const { return Type(d.name); }
std::string Function(const Definition &s) const { return Function(s.name); }
std::string Function(const std::string& prefix, const Definition &s) const {
std::string Function(const Definition& s) const { return Function(s.name); }
std::string Function(const std::string& prefix, const Definition& s) const {
return Function(prefix + s.name);
}
std::string Field(const FieldDef &s) const { return Field(s.name); }
std::string Field(const FieldDef &d, const std::string &s) const {
std::string Field(const FieldDef& s) const { return Field(s.name); }
std::string Field(const FieldDef& d, const std::string& s) const {
return Field(d.name + "_" + s);
}
std::string Variable(const FieldDef &s) const { return Variable(s.name); }
std::string Variable(const FieldDef& s) const { return Variable(s.name); }
std::string Variable(const StructDef &s) const { return Variable(s.name); }
std::string Variable(const StructDef& s) const { return Variable(s.name); }
std::string Variant(const EnumVal &s) const { return Variant(s.name); }
std::string Variant(const EnumVal& s) const { return Variant(s.name); }
std::string EnumVariant(const EnumDef &e, const EnumVal &v) const {
std::string EnumVariant(const EnumDef& e, const EnumVal& v) const {
return Type(e) + config_.enum_variant_seperator + Variant(v);
}
std::string ObjectType(const StructDef &d) const {
std::string ObjectType(const StructDef& d) const {
return ObjectType(d.name);
}
std::string ObjectType(const EnumDef &d) const { return ObjectType(d.name); }
std::string ObjectType(const EnumDef& d) const { return ObjectType(d.name); }
std::string Method(const FieldDef &d, const std::string &suffix) const {
std::string Method(const FieldDef& d, const std::string& suffix) const {
return Method(d.name, suffix);
}
std::string Method(const std::string &prefix, const StructDef &d) const {
std::string Method(const std::string& prefix, const StructDef& d) const {
return Method(prefix, d.name);
}
std::string Method(const std::string &prefix, const FieldDef &d) const {
std::string Method(const std::string& prefix, const FieldDef& d) const {
return Method(prefix, d.name);
}
std::string Method(const std::string &prefix, const FieldDef &d,
const std::string &suffix) const {
std::string Method(const std::string& prefix, const FieldDef& d,
const std::string& suffix) const {
return Method(prefix, d.name, suffix);
}
std::string Namespace(const struct Namespace &ns) const {
std::string Namespace(const struct Namespace& ns) const {
return Namespace(ns.components);
}
std::string NamespacedEnumVariant(const EnumDef &e, const EnumVal &v) const {
std::string NamespacedEnumVariant(const EnumDef& e, const EnumVal& v) const {
return NamespacedString(e.defined_namespace, EnumVariant(e, v));
}
std::string NamespacedType(const Definition &def) const {
std::string NamespacedType(const Definition& def) const {
return NamespacedString(def.defined_namespace, Type(def.name));
}
std::string NamespacedObjectType(const Definition &def) const {
std::string NamespacedObjectType(const Definition& def) const {
return NamespacedString(def.defined_namespace, ObjectType(def.name));
}
std::string Directories(const struct Namespace &ns,
std::string Directories(const struct Namespace& ns,
SkipDir skips = SkipDir::None,
Case input_case = Case::kUpperCamel) const {
return Directories(ns.components, skips, input_case);
@@ -96,19 +96,19 @@ class IdlNamer : public Namer {
// Legacy fields do not really follow the usual config and should be
// considered for deprecation.
std::string LegacyRustNativeVariant(const EnumVal &v) const {
std::string LegacyRustNativeVariant(const EnumVal& v) const {
return ConvertCase(EscapeKeyword(v.name), Case::kUpperCamel);
}
std::string LegacyRustFieldOffsetName(const FieldDef &field) const {
std::string LegacyRustFieldOffsetName(const FieldDef& field) const {
return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper);
}
std::string LegacyRustUnionTypeOffsetName(const FieldDef &field) const {
return "VT_" + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper);
std::string LegacyRustUnionTypeOffsetName(const FieldDef& field) const {
return "VT_" +
ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper);
}
std::string LegacySwiftVariant(const EnumVal &ev) const {
std::string LegacySwiftVariant(const EnumVal& ev) const {
auto name = ev.name;
if (isupper(name.front())) {
std::transform(name.begin(), name.end(), name.begin(), CharToLower);
@@ -117,24 +117,24 @@ class IdlNamer : public Namer {
}
// Also used by Kotlin, lol.
std::string LegacyJavaMethod2(const std::string &prefix, const StructDef &sd,
const std::string &suffix) const {
std::string LegacyJavaMethod2(const std::string& prefix, const StructDef& sd,
const std::string& suffix) const {
return prefix + sd.name + suffix;
}
std::string LegacyKotlinVariant(EnumVal &ev) const {
std::string LegacyKotlinVariant(EnumVal& ev) const {
// Namer assumes the input case is snake case which is wrong...
return ConvertCase(EscapeKeyword(ev.name), Case::kLowerCamel);
}
// Kotlin methods escapes keywords after case conversion but before
// prefixing and suffixing.
std::string LegacyKotlinMethod(const std::string &prefix, const FieldDef &d,
const std::string &suffix) const {
std::string LegacyKotlinMethod(const std::string& prefix, const FieldDef& d,
const std::string& suffix) const {
return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) +
suffix;
}
std::string LegacyKotlinMethod(const std::string &prefix, const StructDef &d,
const std::string &suffix) const {
std::string LegacyKotlinMethod(const std::string& prefix, const StructDef& d,
const std::string& suffix) const {
return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) +
suffix;
}
@@ -145,17 +145,19 @@ class IdlNamer : public Namer {
return "mutate_" + d.name;
}
std::string LegacyRustUnionTypeMethod(const FieldDef &d) {
std::string LegacyRustUnionTypeMethod(const FieldDef& d) {
// assert d is a union
// d should convert case but not escape keywords due to historical reasons
return ConvertCase(d.name, config_.fields, Case::kLowerCamel) + "_type";
}
private:
std::string NamespacedString(const struct Namespace *ns,
const std::string &str) const {
std::string NamespacedString(const struct Namespace* ns,
const std::string& str) const {
std::string ret;
if (ns != nullptr) { ret += Namespace(ns->components); }
if (ns != nullptr) {
ret += Namespace(ns->components);
}
if (!ret.empty()) ret += config_.namespace_seperator;
return ret + str;
}
@@ -163,9 +165,9 @@ class IdlNamer : public Namer {
// This is a temporary helper function for code generators to call until all
// flag-overriding logic into flatc.cpp
inline Namer::Config WithFlagOptions(const Namer::Config &input,
const IDLOptions &opts,
const std::string &path) {
inline Namer::Config WithFlagOptions(const Namer::Config& input,
const IDLOptions& opts,
const std::string& path) {
Namer::Config result = input;
result.object_prefix = opts.object_prefix;
result.object_suffix = opts.object_suffix;

View File

@@ -110,49 +110,49 @@ class Namer {
virtual ~Namer() {}
template<typename T> std::string Method(const T &s) const {
template <typename T>
std::string Method(const T& s) const {
return Method(s.name);
}
virtual std::string Method(const std::string &pre,
const std::string &mid,
const std::string &suf) const {
return Format(pre + "_" + mid + "_" + suf, config_.methods);
virtual std::string Method(const std::string& pre, const std::string& mid,
const std::string& suf) const {
return Format(pre + "_" + mid + "_" + suf, config_.methods);
}
virtual std::string Method(const std::string &pre,
const std::string &suf) const {
virtual std::string Method(const std::string& pre,
const std::string& suf) const {
return Format(pre + "_" + suf, config_.methods);
}
virtual std::string Method(const std::string &s) const {
virtual std::string Method(const std::string& s) const {
return Format(s, config_.methods);
}
virtual std::string Constant(const std::string &s) const {
virtual std::string Constant(const std::string& s) const {
return Format(s, config_.constants);
}
virtual std::string Function(const std::string &s) const {
virtual std::string Function(const std::string& s) const {
return Format(s, config_.functions);
}
virtual std::string Variable(const std::string &s) const {
virtual std::string Variable(const std::string& s) const {
return Format(s, config_.variables);
}
template<typename T>
std::string Variable(const std::string &p, const T &s) const {
template <typename T>
std::string Variable(const std::string& p, const T& s) const {
return Format(p + "_" + s.name, config_.variables);
}
virtual std::string Variable(const std::string &p,
const std::string &s) const {
virtual std::string Variable(const std::string& p,
const std::string& s) const {
return Format(p + "_" + s, config_.variables);
}
virtual std::string Namespace(const std::string &s) const {
virtual std::string Namespace(const std::string& s) const {
return Format(s, config_.namespaces);
}
virtual std::string Namespace(const std::vector<std::string> &ns) const {
virtual std::string Namespace(const std::vector<std::string>& ns) const {
std::string result;
for (auto it = ns.begin(); it != ns.end(); it++) {
if (it != ns.begin()) result += config_.namespace_seperator;
@@ -161,14 +161,14 @@ class Namer {
return result;
}
virtual std::string NamespacedType(const std::vector<std::string> &ns,
const std::string &s) const {
virtual std::string NamespacedType(const std::vector<std::string>& ns,
const std::string& s) const {
return (ns.empty() ? "" : (Namespace(ns) + config_.namespace_seperator)) +
Type(s);
}
// Returns `filename` with the right casing, suffix, and extension.
virtual std::string File(const std::string &filename,
virtual std::string File(const std::string& filename,
SkipFile skips = SkipFile::None) const {
const bool skip_suffix = (skips & SkipFile::Suffix) != SkipFile::None;
const bool skip_ext = (skips & SkipFile::Extension) != SkipFile::None;
@@ -176,8 +176,8 @@ class Namer {
(skip_suffix ? "" : config_.filename_suffix) +
(skip_ext ? "" : config_.filename_extension);
}
template<typename T>
std::string File(const T &f, SkipFile skips = SkipFile::None) const {
template <typename T>
std::string File(const T& f, SkipFile skips = SkipFile::None) const {
return File(f.name, skips);
}
@@ -188,7 +188,7 @@ class Namer {
// input_case is used to tell how to modify namespace. e.g. kUpperCamel will
// add a underscode between case changes, so MyGame turns into My_Game
// (depending also on the output_case).
virtual std::string Directories(const std::vector<std::string> &directories,
virtual std::string Directories(const std::vector<std::string>& directories,
SkipDir skips = SkipDir::None,
Case input_case = Case::kUpperCamel) const {
const bool skip_output_path =
@@ -204,7 +204,7 @@ class Namer {
return result;
}
virtual std::string EscapeKeyword(const std::string &name) const {
virtual std::string EscapeKeyword(const std::string& name) const {
if (keywords_.find(name) == keywords_.end()) {
return name;
} else {
@@ -212,26 +212,26 @@ class Namer {
}
}
virtual std::string Type(const std::string &s) const {
virtual std::string Type(const std::string& s) const {
return Format(s, config_.types);
}
virtual std::string Type(const std::string &t, const std::string &s) const {
virtual std::string Type(const std::string& t, const std::string& s) const {
return Format(t + "_" + s, config_.types);
}
virtual std::string ObjectType(const std::string &s) const {
virtual std::string ObjectType(const std::string& s) const {
return config_.object_prefix + Type(s) + config_.object_suffix;
}
virtual std::string Field(const std::string &s) const {
virtual std::string Field(const std::string& s) const {
return Format(s, config_.fields);
}
virtual std::string Variant(const std::string &s) const {
virtual std::string Variant(const std::string& s) const {
return Format(s, config_.variants);
}
virtual std::string Format(const std::string &s, Case casing) const {
virtual std::string Format(const std::string& s, Case casing) const {
if (config_.escape_keywords == Config::Escape::BeforeConvertingCase) {
return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel);
} else {
@@ -242,8 +242,8 @@ class Namer {
// Denamespaces a string (e.g. The.Quick.Brown.Fox) by returning the last part
// after the `delimiter` (Fox) and placing the rest in `namespace_prefix`
// (The.Quick.Brown).
virtual std::string Denamespace(const std::string &s,
std::string &namespace_prefix,
virtual std::string Denamespace(const std::string& s,
std::string& namespace_prefix,
const char delimiter = '.') const {
const size_t pos = s.find_last_of(delimiter);
if (pos == std::string::npos) {
@@ -255,7 +255,7 @@ class Namer {
}
// Same as above, but disregards the prefix.
virtual std::string Denamespace(const std::string &s,
virtual std::string Denamespace(const std::string& s,
const char delimiter = '.') const {
std::string prefix;
return Denamespace(s, prefix, delimiter);

View File

@@ -7,7 +7,7 @@
namespace flatbuffers {
namespace python {
Version::Version(const std::string &version) {
Version::Version(const std::string& version) {
std::stringstream ss(version);
char dot;
ss >> major >> dot >> minor >> dot >> micro;
@@ -17,7 +17,7 @@ bool Version::IsValid() const {
return (major == 0 || major == 2 || major == 3) && minor >= 0 && micro >= 0;
}
std::set<std::string> Keywords(const Version &version) {
std::set<std::string> Keywords(const Version& version) {
switch (version.major) {
case 2:
// https://docs.python.org/2/reference/lexical_analysis.html#keywords
@@ -44,15 +44,15 @@ std::set<std::string> Keywords(const Version &version) {
}
}
const python::Import &python::Imports::Import(const std::string &module) {
const python::Import& python::Imports::Import(const std::string& module) {
python::Import import;
import.module = module;
imports.push_back(std::move(import));
return imports.back();
}
const python::Import &python::Imports::Import(const std::string &module,
const std::string &name) {
const python::Import& python::Imports::Import(const std::string& module,
const std::string& name) {
python::Import import;
import.module = module;
import.name = name;
@@ -60,15 +60,15 @@ const python::Import &python::Imports::Import(const std::string &module,
return imports.back();
}
const python::Import &python::Imports::Export(const std::string &module) {
const python::Import& python::Imports::Export(const std::string& module) {
python::Import import;
import.module = module;
exports.push_back(std::move(import));
return exports.back();
}
const python::Import &python::Imports::Export(const std::string &module,
const std::string &name) {
const python::Import& python::Imports::Export(const std::string& module,
const std::string& name) {
python::Import import;
import.module = module;
import.name = name;

View File

@@ -62,7 +62,7 @@ static const Namer::Config kStubConfig = {
//
// https://docs.python.org/3/faq/general.html#how-does-the-python-version-numbering-scheme-work
struct Version {
explicit Version(const std::string &version);
explicit Version(const std::string& version);
bool IsValid() const;
@@ -71,7 +71,7 @@ struct Version {
int16_t micro = 0;
};
std::set<std::string> Keywords(const Version &version);
std::set<std::string> Keywords(const Version& version);
struct Import {
bool IsLocal() const { return module == "."; }
@@ -81,13 +81,13 @@ struct Import {
};
struct Imports {
const python::Import &Import(const std::string &module);
const python::Import &Import(const std::string &module,
const std::string &name);
const python::Import& Import(const std::string& module);
const python::Import& Import(const std::string& module,
const std::string& name);
const python::Import &Export(const std::string &module);
const python::Import &Export(const std::string &module,
const std::string &name);
const python::Import& Export(const std::string& module);
const python::Import& Export(const std::string& module,
const std::string& name);
std::vector<python::Import> imports;
std::vector<python::Import> exports;

View File

@@ -18,22 +18,22 @@
#define FLATBUFFERS_FLATC_PCH_H_
// stl
#include <cmath>
#include <sstream>
#include <cassert>
#include <unordered_set>
#include <unordered_map>
#include <iostream>
#include <cmath>
#include <functional>
#include <set>
#include <iostream>
#include <iterator>
#include <set>
#include <sstream>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
// flatbuffers
#include "flatbuffers/pch/pch.h"
#include "flatbuffers/code_generators.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/flexbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/pch/pch.h"
#endif // FLATBUFFERS_FLATC_PCH_H_
#endif // FLATBUFFERS_FLATC_PCH_H_

View File

@@ -18,21 +18,21 @@
#define FLATBUFFERS_PCH_H_
// stl
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <list>
#include <string>
#include <utility>
#include <iomanip>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <limits>
#include <stack>
#include <vector>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// flatbuffers
#include "flatbuffers/util.h"
#endif // FLATBUFFERS_PCH_H_
#endif // FLATBUFFERS_PCH_H_

View File

@@ -3,12 +3,10 @@ package com.google.flatbuffers;
import java.util.Arrays;
/**
* Implements {@code ReadBuf} using an array of bytes
* as a backing storage. Using array of bytes are
* Implements {@code ReadBuf} using an array of bytes as a backing storage. Using array of bytes are
* usually faster than {@code ByteBuffer}.
*
* This class is not thread-safe, meaning that
* it must operate on a single thread. Operating from
* <p>This class is not thread-safe, meaning that it must operate on a single thread. Operating from
* multiple thread leads into a undefined behavior
*/
public class ArrayReadWriteBuf implements ReadWriteBuf {
@@ -51,27 +49,27 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
@Override
public short getShort(int index) {
return (short) ((buffer[index+ 1] << 8) | (buffer[index] & 0xff));
return (short) ((buffer[index + 1] << 8) | (buffer[index] & 0xff));
}
@Override
public int getInt(int index) {
return (((buffer[index + 3]) << 24) |
((buffer[index + 2] & 0xff) << 16) |
((buffer[index + 1] & 0xff) << 8) |
((buffer[index] & 0xff)));
return (((buffer[index + 3]) << 24)
| ((buffer[index + 2] & 0xff) << 16)
| ((buffer[index + 1] & 0xff) << 8)
| ((buffer[index] & 0xff)));
}
@Override
public long getLong(int index) {
return ((((long) buffer[index++] & 0xff)) |
(((long) buffer[index++] & 0xff) << 8) |
(((long) buffer[index++] & 0xff) << 16) |
(((long) buffer[index++] & 0xff) << 24) |
(((long) buffer[index++] & 0xff) << 32) |
(((long) buffer[index++] & 0xff) << 40) |
(((long) buffer[index++] & 0xff) << 48) |
(((long) buffer[index]) << 56));
return ((((long) buffer[index++] & 0xff))
| (((long) buffer[index++] & 0xff) << 8)
| (((long) buffer[index++] & 0xff) << 16)
| (((long) buffer[index++] & 0xff) << 24)
| (((long) buffer[index++] & 0xff) << 32)
| (((long) buffer[index++] & 0xff) << 40)
| (((long) buffer[index++] & 0xff) << 48)
| (((long) buffer[index]) << 56));
}
@Override
@@ -94,17 +92,16 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
return buffer;
}
@Override
public void putBoolean(boolean value) {
setBoolean(writePos, value);
writePos++;
setBoolean(writePos, value);
writePos++;
}
@Override
public void put(byte[] value, int start, int length) {
set(writePos, value, start, length);
writePos+=length;
writePos += length;
}
@Override
@@ -116,36 +113,36 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
@Override
public void putShort(short value) {
setShort(writePos, value);
writePos +=2;
writePos += 2;
}
@Override
public void putInt(int value) {
setInt(writePos, value);
writePos +=4;
writePos += 4;
}
@Override
public void putLong(long value) {
setLong(writePos, value);
writePos +=8;
writePos += 8;
}
@Override
public void putFloat(float value) {
setFloat(writePos, value);
writePos +=4;
writePos += 4;
}
@Override
public void putDouble(double value) {
setDouble(writePos, value);
writePos +=8;
writePos += 8;
}
@Override
public void setBoolean(int index, boolean value) {
set(index, value ? (byte)1 : (byte)0);
set(index, value ? (byte) 1 : (byte) 0);
}
@Override
@@ -165,7 +162,7 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
requestCapacity(index + 2);
buffer[index++] = (byte) ((value) & 0xff);
buffer[index ] = (byte) ((value >> 8) & 0xff);
buffer[index] = (byte) ((value >> 8) & 0xff);
}
@Override
@@ -173,9 +170,9 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
requestCapacity(index + 4);
buffer[index++] = (byte) ((value) & 0xff);
buffer[index++] = (byte) ((value >> 8) & 0xff);
buffer[index++] = (byte) ((value >> 8) & 0xff);
buffer[index++] = (byte) ((value >> 16) & 0xff);
buffer[index ] = (byte) ((value >> 24) & 0xff);
buffer[index] = (byte) ((value >> 24) & 0xff);
}
@Override
@@ -184,14 +181,14 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
int i = (int) value;
buffer[index++] = (byte) ((i) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 16) & 0xff);
buffer[index++] = (byte) ((i >> 24) & 0xff);
i = (int) (value >> 32);
buffer[index++] = (byte) ((i) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 16) & 0xff);
buffer[index ] = (byte) ((i >> 24) & 0xff);
buffer[index] = (byte) ((i >> 24) & 0xff);
}
@Override
@@ -200,9 +197,9 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
int iValue = Float.floatToRawIntBits(value);
buffer[index++] = (byte) ((iValue) & 0xff);
buffer[index++] = (byte) ((iValue >> 8) & 0xff);
buffer[index++] = (byte) ((iValue >> 8) & 0xff);
buffer[index++] = (byte) ((iValue >> 16) & 0xff);
buffer[index ] = (byte) ((iValue >> 24) & 0xff);
buffer[index] = (byte) ((iValue >> 24) & 0xff);
}
@Override
@@ -212,14 +209,14 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
long lValue = Double.doubleToRawLongBits(value);
int i = (int) lValue;
buffer[index++] = (byte) ((i) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 16) & 0xff);
buffer[index++] = (byte) ((i >> 24) & 0xff);
i = (int) (lValue >> 32);
buffer[index++] = (byte) ((i) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 8) & 0xff);
buffer[index++] = (byte) ((i >> 16) & 0xff);
buffer[index ] = (byte) ((i >> 24) & 0xff);
buffer[index] = (byte) ((i >> 24) & 0xff);
}
@Override
@@ -235,7 +232,8 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
@Override
public boolean requestCapacity(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity may not be negative (likely a previous int overflow)");
throw new IllegalArgumentException(
"Capacity may not be negative (likely a previous int overflow)");
}
if (buffer.length >= capacity) {
return true;
@@ -243,7 +241,7 @@ public class ArrayReadWriteBuf implements ReadWriteBuf {
// implemented in the same growing fashion as ArrayList
int oldCapacity = buffer.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity < capacity) { // Note: this also catches newCapacity int overflow
if (newCapacity < capacity) { // Note: this also catches newCapacity int overflow
newCapacity = capacity;
}
buffer = Arrays.copyOf(buffer, newCapacity);

View File

@@ -20,16 +20,17 @@ import java.nio.ByteBuffer;
/// @cond FLATBUFFERS_INTERNAL
/**
* All vector access objects derive from this class, and add their own accessors.
*/
/** All vector access objects derive from this class, and add their own accessors. */
public class BaseVector {
/** Used to hold the vector data position. */
private int vector;
/** Used to hold the vector size. */
private int length;
/** Used to hold the vector element size in table. */
private int element_size;
/** The underlying ByteBuffer to hold the data of the vector. */
protected ByteBuffer bb;
@@ -56,10 +57,10 @@ public class BaseVector {
* Re-init the internal state with an external buffer {@code ByteBuffer}, an offset within and
* element size.
*
* This method exists primarily to allow recycling vector instances without risking memory leaks
* due to {@code ByteBuffer} references.
* <p>This method exists primarily to allow recycling vector instances without risking memory
* leaks due to {@code ByteBuffer} references.
*/
protected void __reset(int _vector, int _element_size, ByteBuffer _bb) {
protected void __reset(int _vector, int _element_size, ByteBuffer _bb) {
bb = _bb;
if (bb != null) {
vector = _vector;
@@ -75,8 +76,8 @@ public class BaseVector {
/**
* Resets the internal state with a null {@code ByteBuffer} and a zero position.
*
* This method exists primarily to allow recycling vector instances without risking memory leaks
* due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* <p>This method exists primarily to allow recycling vector instances without risking memory
* leaks due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* again to a {@code ByteBuffer}.
*/
public void reset() {

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of booleans.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of booleans. */
public final class BooleanVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class BooleanVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public BooleanVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_BYTE, _bb); return this;
__reset(_vector, Constants.SIZEOF_BYTE, _bb);
return this;
}
/**
@@ -43,7 +41,7 @@ public final class BooleanVector extends BaseVector {
* @param j The index from which the boolean will be read.
* @return the boolean value at the given index.
*/
public boolean get(int j) {
public boolean get(int j) {
return 0 != bb.get(__element(j));
}
}

View File

@@ -64,7 +64,7 @@ public class ByteBufferReadWriteBuf implements ReadWriteBuf {
@Override
public void putBoolean(boolean value) {
buffer.put(value ? (byte)1 : (byte)0);
buffer.put(value ? (byte) 1 : (byte) 0);
}
@Override
@@ -104,7 +104,7 @@ public class ByteBufferReadWriteBuf implements ReadWriteBuf {
@Override
public void setBoolean(int index, boolean value) {
set(index, value ? (byte)1 : (byte)0);
set(index, value ? (byte) 1 : (byte) 0);
}
@Override
@@ -166,5 +166,4 @@ public class ByteBufferReadWriteBuf implements ReadWriteBuf {
public boolean requestCapacity(int capacity) {
return capacity <= buffer.limit();
}
}

View File

@@ -24,35 +24,31 @@ import java.nio.ByteBuffer;
/// @addtogroup flatbuffers_java_api
/// @{
/**
* Class that collects utility functions around `ByteBuffer`.
*/
/** Class that collects utility functions around `ByteBuffer`. */
public class ByteBufferUtil {
/**
* Extract the size prefix from a `ByteBuffer`.
*
* @param bb a size-prefixed buffer
* @return the size prefix
*/
public static int getSizePrefix(ByteBuffer bb) {
return bb.getInt(bb.position());
}
/**
* Create a duplicate of a size-prefixed `ByteBuffer` that has its position
* advanced just past the size prefix.
*
* @param bb a size-prefixed buffer
* @return a new buffer on the same underlying data that has skipped the
* size prefix
*/
public static ByteBuffer removeSizePrefix(ByteBuffer bb) {
ByteBuffer s = bb.duplicate();
s.position(s.position() + SIZE_PREFIX_LENGTH);
return s;
}
/**
* Extract the size prefix from a `ByteBuffer`.
*
* @param bb a size-prefixed buffer
* @return the size prefix
*/
public static int getSizePrefix(ByteBuffer bb) {
return bb.getInt(bb.position());
}
/**
* Create a duplicate of a size-prefixed `ByteBuffer` that has its position advanced just past the
* size prefix.
*
* @param bb a size-prefixed buffer
* @return a new buffer on the same underlying data that has skipped the size prefix
*/
public static ByteBuffer removeSizePrefix(ByteBuffer bb) {
ByteBuffer s = bb.duplicate();
s.position(s.position() + SIZE_PREFIX_LENGTH);
return s;
}
}
/// @}

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of signed or unsigned 8-bit values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of signed or unsigned 8-bit values. */
public final class ByteVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class ByteVector extends BaseVector {
* @param vector Start data of a vector.
* @param bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public ByteVector __assign(int vector, ByteBuffer bb) {
__reset(vector, Constants.SIZEOF_BYTE, bb); return this;
public ByteVector __assign(int vector, ByteBuffer bb) {
__reset(vector, Constants.SIZEOF_BYTE, bb);
return this;
}
/**
@@ -44,12 +42,12 @@ public final class ByteVector extends BaseVector {
* @return the 8-bit value at the given index.
*/
public byte get(int j) {
return bb.get(__element(j));
return bb.get(__element(j));
}
/**
* Reads the byte at the given index, zero-extends it to type int, and returns the result,
* which is therefore in the range 0 through 255.
* Reads the byte at the given index, zero-extends it to type int, and returns the result, which
* is therefore in the range 0 through 255.
*
* @param j The index from which the byte will be read.
* @return the unsigned 8-bit at the given index.

View File

@@ -18,35 +18,40 @@ package com.google.flatbuffers;
/// @cond FLATBUFFERS_INTERNAL
/**
* Class that holds shared constants
*/
/** Class that holds shared constants */
public class Constants {
// Java doesn't seem to have these.
/** The number of bytes in an `byte`. */
static final int SIZEOF_BYTE = 1;
/** The number of bytes in a `short`. */
static final int SIZEOF_SHORT = 2;
/** The number of bytes in an `int`. */
static final int SIZEOF_INT = 4;
/** The number of bytes in an `float`. */
static final int SIZEOF_FLOAT = 4;
/** The number of bytes in an `long`. */
static final int SIZEOF_LONG = 8;
/** The number of bytes in an `double`. */
static final int SIZEOF_DOUBLE = 8;
/** The number of bytes in a file identifier. */
static final int FILE_IDENTIFIER_LENGTH = 4;
/** The number of bytes in a size prefix. */
public static final int SIZE_PREFIX_LENGTH = 4;
/** A version identifier to force a compile error if someone
accidentally tries to build generated code with a runtime of
two mismatched version. Versions need to always match, as
the runtime and generated code are modified in sync.
Changes to the Java implementation need to be sure to change
the version here and in the code generator on every possible
incompatible change */
public static void FLATBUFFERS_25_2_10() {}
// Java doesn't seem to have these.
/** The number of bytes in an `byte`. */
static final int SIZEOF_BYTE = 1;
/** The number of bytes in a `short`. */
static final int SIZEOF_SHORT = 2;
/** The number of bytes in an `int`. */
static final int SIZEOF_INT = 4;
/** The number of bytes in an `float`. */
static final int SIZEOF_FLOAT = 4;
/** The number of bytes in an `long`. */
static final int SIZEOF_LONG = 8;
/** The number of bytes in an `double`. */
static final int SIZEOF_DOUBLE = 8;
/** The number of bytes in a file identifier. */
static final int FILE_IDENTIFIER_LENGTH = 4;
/** The number of bytes in a size prefix. */
public static final int SIZE_PREFIX_LENGTH = 4;
/**
* A version identifier to force a compile error if someone accidentally tries to build generated
* code with a runtime of two mismatched version. Versions need to always match, as the runtime
* and generated code are modified in sync. Changes to the Java implementation need to be sure to
* change the version here and in the code generator on every possible incompatible change
*/
public static void FLATBUFFERS_25_2_10() {}
}
/// @endcond

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of double values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of double values. */
public final class DoubleVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class DoubleVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public DoubleVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_DOUBLE, _bb); return this;
__reset(_vector, Constants.SIZEOF_DOUBLE, _bb);
return this;
}
/**

File diff suppressed because it is too large Load Diff

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of float values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of float values. */
public final class FloatVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class FloatVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public FloatVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_FLOAT, _bb); return this;
__reset(_vector, Constants.SIZEOF_FLOAT, _bb);
return this;
}
/**
@@ -43,7 +41,7 @@ public final class FloatVector extends BaseVector {
* @param j The index from which the float value will be read.
* @return the float value at the given index.
*/
public float get(int j) {
public float get(int j) {
return bb.getFloat(__element(j));
}
}

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of signed or unsigned 32-bit values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of signed or unsigned 32-bit values. */
public final class IntVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class IntVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public IntVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_INT, _bb); return this;
__reset(_vector, Constants.SIZEOF_INT, _bb);
return this;
}
/**

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of long values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of long values. */
public final class LongVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class LongVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public LongVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_LONG, _bb); return this;
__reset(_vector, Constants.SIZEOF_LONG, _bb);
return this;
}
/**

View File

@@ -1,12 +1,11 @@
package com.google.flatbuffers;
/**
* Represent a chunk of data, where FlexBuffers will read from.
*/
/** Represent a chunk of data, where FlexBuffers will read from. */
public interface ReadBuf {
/**
* Read boolean from data. Booleans as stored as single byte
*
* @param index position of the element in ReadBuf
* @return boolean element
*/
@@ -14,6 +13,7 @@ public interface ReadBuf {
/**
* Read a byte from data.
*
* @param index position of the element in ReadBuf
* @return a byte
*/
@@ -21,6 +21,7 @@ public interface ReadBuf {
/**
* Read a short from data.
*
* @param index position of the element in ReadBuf
* @return a short
*/
@@ -28,6 +29,7 @@ public interface ReadBuf {
/**
* Read a 32-bit int from data.
*
* @param index position of the element in ReadBuf
* @return an int
*/
@@ -35,6 +37,7 @@ public interface ReadBuf {
/**
* Read a 64-bit long from data.
*
* @param index position of the element in ReadBuf
* @return a long
*/
@@ -42,6 +45,7 @@ public interface ReadBuf {
/**
* Read a 32-bit float from data.
*
* @param index position of the element in ReadBuf
* @return a float
*/
@@ -49,6 +53,7 @@ public interface ReadBuf {
/**
* Read a 64-bit float from data.
*
* @param index position of the element in ReadBuf
* @return a double
*/
@@ -56,6 +61,7 @@ public interface ReadBuf {
/**
* Read an UTF-8 string from data.
*
* @param start initial element of the string
* @param size size of the string in bytes.
* @return a {@code String}
@@ -63,19 +69,19 @@ public interface ReadBuf {
String getString(int start, int size);
/**
* Expose ReadBuf as an array of bytes.
* This method is meant to be as efficient as possible, so for a array-backed ReadBuf, it should
* return its own internal data. In case access to internal data is not possible,
* a copy of the data into an array of bytes might occur.
* Expose ReadBuf as an array of bytes. This method is meant to be as efficient as possible, so
* for a array-backed ReadBuf, it should return its own internal data. In case access to internal
* data is not possible, a copy of the data into an array of bytes might occur.
*
* @return ReadBuf as an array of bytes
*/
byte[] data();
/**
* Defines the size of the message in the buffer. It also determines last position that buffer
* can be read. Last byte to be accessed is in position {@code limit() -1}.
* Defines the size of the message in the buffer. It also determines last position that buffer can
* be read. Last byte to be accessed is in position {@code limit() -1}.
*
* @return indicate last position
*/
int limit();
}

View File

@@ -6,137 +6,144 @@ package com.google.flatbuffers;
*/
public interface ReadWriteBuf extends ReadBuf {
/**
* Clears (resets) the buffer so that it can be reused. Write position will be set to the
* start.
*/
void clear();
/**
* Clears (resets) the buffer so that it can be reused. Write position will be set to the start.
*/
void clear();
/**
* Put a boolean into the buffer at {@code writePosition()} . Booleans as stored as single
* byte. Write position will be incremented.
* @return boolean element
*/
void putBoolean(boolean value);
/**
* Put a boolean into the buffer at {@code writePosition()} . Booleans as stored as single byte.
* Write position will be incremented.
*
* @return boolean element
*/
void putBoolean(boolean value);
/**
* Put an array of bytes into the buffer at {@code writePosition()}. Write position will be
* incremented.
* @param value the data to be copied
* @param start initial position on value to be copied
* @param length amount of bytes to be copied
*/
void put (byte[] value, int start, int length);
/**
* Put an array of bytes into the buffer at {@code writePosition()}. Write position will be
* incremented.
*
* @param value the data to be copied
* @param start initial position on value to be copied
* @param length amount of bytes to be copied
*/
void put(byte[] value, int start, int length);
/**
* Write a byte into the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void put(byte value);
/**
* Write a byte into the buffer at {@code writePosition()}. Write position will be incremented.
*/
void put(byte value);
/**
* Write a 16-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putShort(short value);
/**
* Write a 16-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putShort(short value);
/**
* Write a 32-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putInt(int value);
/**
* Write a 32-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putInt(int value);
/**
* Write a 64-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putLong(long value);
/**
* Write a 64-bit into in the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putLong(long value);
/**
* Write a 32-bit float into the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putFloat(float value);
/**
* Write a 32-bit float into the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putFloat(float value);
/**
* Write a 64-bit float into the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putDouble(double value);
/**
* Write a 64-bit float into the buffer at {@code writePosition()}. Write position will be
* incremented.
*/
void putDouble(double value);
/**
* Write boolean into a given position on the buffer. Booleans as stored as single byte.
* @param index position of the element in buffer
*/
void setBoolean(int index, boolean value);
/**
* Write boolean into a given position on the buffer. Booleans as stored as single byte.
*
* @param index position of the element in buffer
*/
void setBoolean(int index, boolean value);
/**
* Read a byte from data.
* @param index position of the element in the buffer
* @return a byte
*/
void set(int index, byte value);
/**
* Read a byte from data.
*
* @param index position of the element in the buffer
* @return a byte
*/
void set(int index, byte value);
/**
* Write an array of bytes into the buffer.
* @param index initial position of the buffer to be written
* @param value the data to be copied
* @param start initial position on value to be copied
* @param length amount of bytes to be copied
*/
void set(int index, byte[] value, int start, int length);
/**
* Write an array of bytes into the buffer.
*
* @param index initial position of the buffer to be written
* @param value the data to be copied
* @param start initial position on value to be copied
* @param length amount of bytes to be copied
*/
void set(int index, byte[] value, int start, int length);
/**
* Read a short from data.
* @param index position of the element in ReadBuf
* @return a short
*/
void setShort(int index, short value);
/**
* Read a short from data.
*
* @param index position of the element in ReadBuf
* @return a short
*/
void setShort(int index, short value);
/**
* Read a 32-bit int from data.
* @param index position of the element in ReadBuf
* @return an int
*/
void setInt(int index, int value);
/**
* Read a 32-bit int from data.
*
* @param index position of the element in ReadBuf
* @return an int
*/
void setInt(int index, int value);
/**
* Read a 64-bit long from data.
* @param index position of the element in ReadBuf
* @return a long
*/
void setLong(int index, long value);
/**
* Read a 64-bit long from data.
*
* @param index position of the element in ReadBuf
* @return a long
*/
void setLong(int index, long value);
/**
* Read a 32-bit float from data.
* @param index position of the element in ReadBuf
* @return a float
*/
void setFloat(int index, float value);
/**
* Read a 32-bit float from data.
*
* @param index position of the element in ReadBuf
* @return a float
*/
void setFloat(int index, float value);
/**
* Read a 64-bit float from data.
* @param index position of the element in ReadBuf
* @return a double
*/
void setDouble(int index, double value);
/**
* Read a 64-bit float from data.
*
* @param index position of the element in ReadBuf
* @return a double
*/
void setDouble(int index, double value);
int writePosition();
int writePosition();
/**
* Defines the size of the message in the buffer. It also determines last position that buffer
* can be read or write. Last byte to be accessed is in position {@code limit() -1}.
* @return indicate last position
*/
int limit();
/**
* Defines the size of the message in the buffer. It also determines last position that buffer can
* be read or write. Last byte to be accessed is in position {@code limit() -1}.
*
* @return indicate last position
*/
int limit();
/**
* Request capacity of the buffer. In case buffer is already larger
* than the requested, this method will just return true. Otherwise
* It might try to resize the buffer.
*
* @return true if buffer is able to offer
* the requested capacity
*/
boolean requestCapacity(int capacity);
/**
* Request capacity of the buffer. In case buffer is already larger than the requested, this
* method will just return true. Otherwise It might try to resize the buffer.
*
* @return true if buffer is able to offer the requested capacity
*/
boolean requestCapacity(int capacity);
}

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of signed or unsigned 16-bit values.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of signed or unsigned 16-bit values. */
public final class ShortVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -31,10 +28,11 @@ public final class ShortVector extends BaseVector {
* @param _vector Start data of a vector.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public ShortVector __assign(int _vector, ByteBuffer _bb) {
__reset(_vector, Constants.SIZEOF_SHORT, _bb); return this;
__reset(_vector, Constants.SIZEOF_SHORT, _bb);
return this;
}
/**
@@ -48,8 +46,8 @@ public final class ShortVector extends BaseVector {
}
/**
* Reads the short at the given index, zero-extends it to type int, and returns the result,
* which is therefore in the range 0 through 65535.
* Reads the short at the given index, zero-extends it to type int, and returns the result, which
* is therefore in the range 0 through 65535.
*
* @param j The index from which the short value will be read.
* @return the unsigned 16-bit at the given index.

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of String.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of String. */
public final class StringVector extends BaseVector {
private Utf8 utf8 = Utf8.getDefault();
@@ -34,10 +31,11 @@ public final class StringVector extends BaseVector {
* @param _element_size Size of a vector element.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public StringVector __assign(int _vector, int _element_size, ByteBuffer _bb) {
__reset(_vector, _element_size, _bb); return this;
__reset(_vector, _element_size, _bb);
return this;
}
/**

View File

@@ -20,22 +20,21 @@ import java.nio.ByteBuffer;
/// @cond FLATBUFFERS_INTERNAL
/**
* All structs in the generated code derive from this class, and add their own accessors.
*/
/** All structs in the generated code derive from this class, and add their own accessors. */
public class Struct {
/** Used to hold the position of the `bb` buffer. */
protected int bb_pos;
/** The underlying ByteBuffer to hold the data of the Struct. */
protected ByteBuffer bb;
/**
* Re-init the internal state with an external buffer {@code ByteBuffer} and an offset within.
*
* This method exists primarily to allow recycling Table instances without risking memory leaks
* <p>This method exists primarily to allow recycling Table instances without risking memory leaks
* due to {@code ByteBuffer} references.
*/
protected void __reset(int _i, ByteBuffer _bb) {
protected void __reset(int _i, ByteBuffer _bb) {
bb = _bb;
if (bb != null) {
bb_pos = _i;
@@ -47,8 +46,8 @@ public class Struct {
/**
* Resets internal state with a null {@code ByteBuffer} and a zero position.
*
* This method exists primarily to allow recycling Struct instances without risking memory leaks
* due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* <p>This method exists primarily to allow recycling Struct instances without risking memory
* leaks due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* again to a {@code ByteBuffer}.
*
* @param struct the instance to reset to initial state

View File

@@ -17,23 +17,26 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/// @cond FLATBUFFERS_INTERNAL
/**
* All tables in the generated code derive from this class, and add their own accessors.
*/
/** All tables in the generated code derive from this class, and add their own accessors. */
public class Table {
/** Used to hold the position of the `bb` buffer. */
protected int bb_pos;
/** The underlying ByteBuffer to hold the data of the Table. */
protected ByteBuffer bb;
/** Used to hold the vtable position. */
private int vtable_start;
/** Used to hold the vtable size. */
private int vtable_size;
Utf8 utf8 = Utf8.getDefault();
/**
@@ -41,7 +44,9 @@ public class Table {
*
* @return Returns the Table's ByteBuffer.
*/
public ByteBuffer getByteBuffer() { return bb; }
public ByteBuffer getByteBuffer() {
return bb;
}
/**
* Look up a field in the vtable.
@@ -82,10 +87,10 @@ public class Table {
/**
* Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
*
* This allocates a new string and converts to wide chars upon each access,
* which is not very efficient. Instead, each FlatBuffer string also comes with an
* accessor based on __vector_as_bytebuffer below, which is much more efficient,
* assuming your Java program can handle UTF-8 data directly.
* <p>This allocates a new string and converts to wide chars upon each access, which is not very
* efficient. Instead, each FlatBuffer string also comes with an accessor based on
* __vector_as_bytebuffer below, which is much more efficient, assuming your Java program can
* handle UTF-8 data directly.
*
* @param offset An `int` index into the Table's ByteBuffer.
* @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
@@ -97,10 +102,10 @@ public class Table {
/**
* Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
*
* This allocates a new string and converts to wide chars upon each access,
* which is not very efficient. Instead, each FlatBuffer string also comes with an
* accessor based on __vector_as_bytebuffer below, which is much more efficient,
* assuming your Java program can handle UTF-8 data directly.
* <p>This allocates a new string and converts to wide chars upon each access, which is not very
* efficient. Instead, each FlatBuffer string also comes with an accessor based on
* __vector_as_bytebuffer below, which is much more efficient, assuming your Java program can
* handle UTF-8 data directly.
*
* @param offset An `int` index into the Table's ByteBuffer.
* @param bb Table ByteBuffer used to read a string at given offset.
@@ -133,15 +138,15 @@ public class Table {
*/
protected int __vector(int offset) {
offset += bb_pos;
return offset + bb.getInt(offset) + SIZEOF_INT; // data starts after the length
return offset + bb.getInt(offset) + SIZEOF_INT; // data starts after the length
}
/**
* Get a whole vector as a ByteBuffer.
*
* This is efficient, since it only allocates a new {@link ByteBuffer} object,
* but does not actually copy the data, it still refers to the same bytes
* as the original ByteBuffer. Also useful with nested FlatBuffers, etc.
* <p>This is efficient, since it only allocates a new {@link ByteBuffer} object, but does not
* actually copy the data, it still refers to the same bytes as the original ByteBuffer. Also
* useful with nested FlatBuffers, etc.
*
* @param vector_offset The position of the vector in the byte buffer
* @param elem_size The size of each element in the array
@@ -160,8 +165,8 @@ public class Table {
/**
* Initialize vector as a ByteBuffer.
*
* This is more efficient than using duplicate, since it doesn't copy the data
* nor allocattes a new {@link ByteBuffer}, creating no garbage to be collected.
* <p>This is more efficient than using duplicate, since it doesn't copy the data nor allocattes a
* new {@link ByteBuffer}, creating no garbage to be collected.
*
* @param bb The {@link ByteBuffer} for the array
* @param vector_offset The position of the vector in the byte buffer
@@ -205,17 +210,16 @@ public class Table {
/**
* Check if a {@link ByteBuffer} contains a file identifier.
*
* @param bb A {@code ByteBuffer} to check if it contains the identifier
* `ident`.
* @param bb A {@code ByteBuffer} to check if it contains the identifier `ident`.
* @param ident A `String` identifier of the FlatBuffer file.
* @return True if the buffer contains the file identifier
*/
protected static boolean __has_identifier(ByteBuffer bb, String ident) {
if (ident.length() != FILE_IDENTIFIER_LENGTH)
throw new AssertionError("FlatBuffers: file identifier must be length " +
FILE_IDENTIFIER_LENGTH);
throw new AssertionError(
"FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH);
for (int i = 0; i < FILE_IDENTIFIER_LENGTH; i++) {
if (ident.charAt(i) != (char)bb.get(bb.position() + SIZEOF_INT + i)) return false;
if (ident.charAt(i) != (char) bb.get(bb.position() + SIZEOF_INT + i)) return false;
}
return true;
}
@@ -229,11 +233,13 @@ public class Table {
protected void sortTables(int[] offsets, final ByteBuffer bb) {
Integer[] off = new Integer[offsets.length];
for (int i = 0; i < offsets.length; i++) off[i] = offsets[i];
java.util.Arrays.sort(off, new java.util.Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return keysCompare(o1, o2, bb);
}
});
java.util.Arrays.sort(
off,
new java.util.Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return keysCompare(o1, o2, bb);
}
});
for (int i = 0; i < offsets.length; i++) offsets[i] = off[i];
}
@@ -244,7 +250,9 @@ public class Table {
* @param o2 An 'Integer' index of the second key into the bb.
* @param bb A {@code ByteBuffer} to get the keys.
*/
protected int keysCompare(Integer o1, Integer o2, ByteBuffer bb) { return 0; }
protected int keysCompare(Integer o1, Integer o2, ByteBuffer bb) {
return 0;
}
/**
* Compare two strings in the buffer.
@@ -261,7 +269,7 @@ public class Table {
int startPos_1 = offset_1 + SIZEOF_INT;
int startPos_2 = offset_2 + SIZEOF_INT;
int len = Math.min(len_1, len_2);
for(int i = 0; i < len; i++) {
for (int i = 0; i < len; i++) {
if (bb.get(i + startPos_1) != bb.get(i + startPos_2))
return bb.get(i + startPos_1) - bb.get(i + startPos_2);
}
@@ -282,8 +290,7 @@ public class Table {
int startPos_1 = offset_1 + Constants.SIZEOF_INT;
int len = Math.min(len_1, len_2);
for (int i = 0; i < len; i++) {
if (bb.get(i + startPos_1) != key[i])
return bb.get(i + startPos_1) - key[i];
if (bb.get(i + startPos_1) != key[i]) return bb.get(i + startPos_1) - key[i];
}
return len_1 - len_2;
}
@@ -291,10 +298,10 @@ public class Table {
/**
* Re-init the internal state with an external buffer {@code ByteBuffer} and an offset within.
*
* This method exists primarily to allow recycling Table instances without risking memory leaks
* <p>This method exists primarily to allow recycling Table instances without risking memory leaks
* due to {@code ByteBuffer} references.
*/
protected void __reset(int _i, ByteBuffer _bb) {
protected void __reset(int _i, ByteBuffer _bb) {
bb = _bb;
if (bb != null) {
bb_pos = _i;
@@ -310,9 +317,9 @@ public class Table {
/**
* Resets the internal state with a null {@code ByteBuffer} and a zero position.
*
* This method exists primarily to allow recycling Table instances without risking memory leaks
* due to {@code ByteBuffer} references. The instance will be unusable until it is assigned
* again to a {@code ByteBuffer}.
* <p>This method exists primarily to allow recycling Table instances without risking memory leaks
* due to {@code ByteBuffer} references. The instance will be unusable until it is assigned again
* to a {@code ByteBuffer}.
*/
public void __reset() {
__reset(0, null);

View File

@@ -17,13 +17,10 @@
package com.google.flatbuffers;
import static com.google.flatbuffers.Constants.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Helper type for accessing vector of unions.
*/
import java.nio.ByteBuffer;
/** Helper type for accessing vector of unions. */
public final class UnionVector extends BaseVector {
/**
* Assigns vector access object to vector data.
@@ -32,13 +29,13 @@ public final class UnionVector extends BaseVector {
* @param _element_size Size of a vector element.
* @param _bb Table's ByteBuffer.
* @return Returns current vector access object assigned to vector data whose offset is stored at
* `vector`.
* `vector`.
*/
public UnionVector __assign(int _vector, int _element_size, ByteBuffer _bb) {
__reset(_vector, _element_size, _bb); return this;
__reset(_vector, _element_size, _bb);
return this;
}
/**
* Initialize any Table-derived type to point to the union at the given `index`.
*

View File

@@ -16,22 +16,22 @@
package com.google.flatbuffers;
import java.nio.ByteBuffer;
import static java.lang.Character.MAX_SURROGATE;
import static java.lang.Character.MIN_SURROGATE;
import static java.lang.Character.MIN_HIGH_SURROGATE;
import static java.lang.Character.MIN_LOW_SURROGATE;
import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;
import static java.lang.Character.MIN_SURROGATE;
import static java.lang.Character.isSurrogatePair;
import static java.lang.Character.toCodePoint;
import java.nio.ByteBuffer;
public abstract class Utf8 {
/**
* Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string,
* this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in
* both time and space.
* Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this
* method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both
* time and space.
*
* @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
* surrogates)
@@ -60,6 +60,7 @@ public abstract class Utf8 {
/**
* Get the default UTF-8 processor.
*
* @return the default processor
*/
public static Utf8 getDefault() {
@@ -71,6 +72,7 @@ public abstract class Utf8 {
/**
* Set the default instance of the UTF-8 processor.
*
* @param instance the new instance to use
*/
public static void setDefault(Utf8 instance) {
@@ -79,6 +81,7 @@ public abstract class Utf8 {
/**
* Encode a Java's CharSequence UTF8 codepoint into a byte array.
*
* @param in CharSequence to be encoded
* @param start start position of the first char in the codepoint
* @param out byte array of 4 bytes to be filled
@@ -94,11 +97,11 @@ public abstract class Utf8 {
}
char c = in.charAt(start);
if (c < 0x80) {
// One byte (0xxx xxxx)
out[0] = (byte) c;
return 1;
} else if (c < 0x800) {
if (c < 0x80) {
// One byte (0xxx xxxx)
out[0] = (byte) c;
return 1;
} else if (c < 0x800) {
// Two bytes (110x xxxx 10xx xxxx)
out[0] = (byte) (0xC0 | (c >>> 6));
out[1] = (byte) (0x80 | (0x3F & c));
@@ -107,7 +110,7 @@ public abstract class Utf8 {
// Three bytes (1110 xxxx 10xx xxxx 10xx xxxx)
// Maximum single-char code point is 0xFFFF, 16 bits.
out[0] = (byte) (0xE0 | (c >>> 12));
out[1] =(byte) (0x80 | (0x3F & (c >>> 6)));
out[1] = (byte) (0x80 | (0x3F & (c >>> 6)));
out[2] = (byte) (0x80 | (0x3F & c));
return 3;
} else {
@@ -115,7 +118,7 @@ public abstract class Utf8 {
// Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8
// bytes
final char low;
if (start + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(start+1)))) {
if (start + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(start + 1)))) {
throw new UnpairedSurrogateException(start, inLength);
}
int codePoint = toCodePoint(c, low);
@@ -134,23 +137,17 @@ public abstract class Utf8 {
*/
static class DecodeUtil {
/**
* Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'.
*/
/** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */
static boolean isOneByte(byte b) {
return b >= 0;
}
/**
* Returns whether this is a two-byte codepoint with the form '10XXXXXX'.
*/
/** Returns whether this is a two-byte codepoint with the form '10XXXXXX'. */
static boolean isTwoBytes(byte b) {
return b < (byte) 0xE0;
}
/**
* Returns whether this is a three-byte codepoint with the form '110XXXXX'.
*/
/** Returns whether this is a three-byte codepoint with the form '110XXXXX'. */
static boolean isThreeBytes(byte b) {
return b < (byte) 0xF0;
}
@@ -159,8 +156,7 @@ public abstract class Utf8 {
resultArr[resultPos] = (char) byte1;
}
static void handleTwoBytes(
byte byte1, byte byte2, char[] resultArr, int resultPos)
static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos)
throws IllegalArgumentException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
@@ -177,58 +173,56 @@ public abstract class Utf8 {
byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos)
throws IllegalArgumentException {
if (isNotTrailingByte(byte2)
// overlong? 5 most significant bits must not all be zero
|| (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0)
// check for illegal surrogate codepoints
|| (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0)
|| isNotTrailingByte(byte3)) {
// overlong? 5 most significant bits must not all be zero
|| (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0)
// check for illegal surrogate codepoints
|| (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0)
|| isNotTrailingByte(byte3)) {
throw new IllegalArgumentException("Invalid UTF-8");
}
resultArr[resultPos] = (char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
resultArr[resultPos] =
(char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
}
static void handleFourBytes(
byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos)
throws IllegalArgumentException{
throws IllegalArgumentException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
throw new IllegalArgumentException("Invalid UTF-8");
}
int codepoint = ((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
int codepoint =
((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint);
resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint);
}
/**
* Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
*/
/** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */
private static boolean isNotTrailingByte(byte b) {
return b > (byte) 0xBF;
}
/**
* Returns the actual value of the trailing byte (removes the prefix '10') for composition.
*/
/** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */
private static int trailingByteValue(byte b) {
return b & 0x3F;
}
private static char highSurrogate(int codePoint) {
return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10))
+ (codePoint >>> 10));
return (char)
((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10));
}
private static char lowSurrogate(int codePoint) {
@@ -236,7 +230,8 @@ public abstract class Utf8 {
}
}
// These UTF-8 handling methods are copied from Guava's Utf8Unsafe class with a modification to throw
// These UTF-8 handling methods are copied from Guava's Utf8Unsafe class with a modification to
// throw
// a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can
// fallback to more lenient behavior.
static class UnpairedSurrogateException extends IllegalArgumentException {

Some files were not shown because too many files have changed in this diff Show More