Commit 9a1f7be6 authored by evolutional's avatar evolutional Committed by Wouter van Oortmerssen

Initial commit of .NET port of FlatBuffers

Include C# codegen in flatc and .NET FlatBuffer access via the
FlatBufferBuilder class

Tested: on Windows.

Change-Id: If5228a8df60a10e0751b245c6c64530264ea2d8a
parent 3f85183c
...@@ -38,4 +38,3 @@ CMakeLists.txt.user ...@@ -38,4 +38,3 @@ CMakeLists.txt.user
CMakeScripts/** CMakeScripts/**
build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/** build/Xcode/FlatBuffers.xcodeproj/project.xcworkspace/**
build/Xcode/FlatBuffers.xcodeproj/xcuserdata/** build/Xcode/FlatBuffers.xcodeproj/xcuserdata/**
...@@ -13,6 +13,7 @@ set(FlatBuffers_Compiler_SRCS ...@@ -13,6 +13,7 @@ set(FlatBuffers_Compiler_SRCS
src/idl_parser.cpp src/idl_parser.cpp
src/idl_gen_cpp.cpp src/idl_gen_cpp.cpp
src/idl_gen_java.cpp src/idl_gen_java.cpp
src/idl_gen_csharp.cpp
src/idl_gen_go.cpp src/idl_gen_go.cpp
src/idl_gen_text.cpp src/idl_gen_text.cpp
src/flatc.cpp src/flatc.cpp
......
...@@ -266,6 +266,7 @@ ...@@ -266,6 +266,7 @@
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" /> <ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
<ClInclude Include="..\..\include\flatbuffers\idl.h" /> <ClInclude Include="..\..\include\flatbuffers\idl.h" />
<ClInclude Include="..\..\include\flatbuffers\util.h" /> <ClInclude Include="..\..\include\flatbuffers\util.h" />
<ClCompile Include="..\..\src\idl_gen_csharp.cpp" />
<ClCompile Include="..\..\src\idl_gen_go.cpp"> <ClCompile Include="..\..\src\idl_gen_go.cpp">
<WarningLevel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Level4</WarningLevel> <WarningLevel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Level4</WarningLevel>
</ClCompile> </ClCompile>
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory> <LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-j -c -n -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory> <LocalDebuggerWorkingDirectory>..\..</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor> <DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-j -c -n -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
......
File mode changed from 100755 to 100644
...@@ -386,6 +386,14 @@ extern bool GenerateJava(const Parser &parser, ...@@ -386,6 +386,14 @@ extern bool GenerateJava(const Parser &parser,
const std::string &file_name, const std::string &file_name,
const GeneratorOptions &opts); const GeneratorOptions &opts);
// Generate C# files from the definitions in the Parser object.
// See idl_gen_csharp.cpp.
extern bool GenerateCSharp(const Parser &parser,
const std::string &path,
const std::string &file_name,
const GeneratorOptions &opts);
} // namespace flatbuffers } // namespace flatbuffers
#endif // FLATBUFFERS_IDL_H_ #endif // FLATBUFFERS_IDL_H_
......
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
namespace FlatBuffers
{
/// <summary>
/// Class to mimick Java's ByteBuffer which is used heavily in Flatbuffers
/// </summary>
public class ByteBuffer
{
private readonly byte[] _buffer;
public int Length { get { return _buffer.Length; } }
public byte[] Data { get { return _buffer; } }
public ByteBuffer(byte[] buffer)
{
_buffer = buffer;
}
protected void WriteLittleEndian(int offset, byte[] data)
{
if (!BitConverter.IsLittleEndian)
{
data = data.Reverse().ToArray();
}
Buffer.BlockCopy(data, 0, _buffer, offset, data.Length);
}
protected byte[] ReadLittleEndian(int offset, int count)
{
AssertOffsetAndLength(offset, count);
var tmp = new byte[count];
Buffer.BlockCopy(_buffer, offset, tmp, 0, count);
return (BitConverter.IsLittleEndian)
? tmp
: tmp.Reverse().ToArray();
}
private void AssertOffsetAndLength(int offset, int length)
{
if (offset < 0 ||
offset >= _buffer.Length ||
offset + length > _buffer.Length)
throw new ArgumentOutOfRangeException();
}
public void PutByte(int offset, byte value)
{
AssertOffsetAndLength(offset, sizeof(byte));
_buffer[offset] = value;
}
public void PutShort(int offset, short value)
{
AssertOffsetAndLength(offset, sizeof(short));
WriteLittleEndian(offset, BitConverter.GetBytes(value));
}
public void PutInt(int offset, int value)
{
AssertOffsetAndLength(offset, sizeof(int));
WriteLittleEndian(offset, BitConverter.GetBytes(value));
}
public void PutLong(int offset, long value)
{
AssertOffsetAndLength(offset, sizeof(long));
WriteLittleEndian(offset, BitConverter.GetBytes(value));
}
public void PutFloat(int offset, float value)
{
AssertOffsetAndLength(offset, sizeof(float));
WriteLittleEndian(offset, BitConverter.GetBytes(value));
}
public void PutDouble(int offset, double value)
{
AssertOffsetAndLength(offset, sizeof(double));
WriteLittleEndian(offset, BitConverter.GetBytes(value));
}
public byte Get(int index)
{
AssertOffsetAndLength(index, sizeof(byte));
return _buffer[index];
}
public short GetShort(int index)
{
var tmp = ReadLittleEndian(index, sizeof(short));
var value = BitConverter.ToInt16(tmp, 0);
return value;
}
public int GetInt(int index)
{
var tmp = ReadLittleEndian(index, sizeof(int));
var value = BitConverter.ToInt32(tmp, 0);
return value;
}
public long GetLong(int index)
{
var tmp = ReadLittleEndian(index, sizeof(long));
var value = BitConverter.ToInt64(tmp, 0);
return value;
}
public float GetFloat(int index)
{
var tmp = ReadLittleEndian(index, sizeof(float));
var value = BitConverter.ToSingle(tmp, 0);
return value;
}
public double GetDouble(int index)
{
var tmp = ReadLittleEndian(index, sizeof(double));
var value = BitConverter.ToDouble(tmp, 0);
return value;
}
}
}
This diff is collapsed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlatBuffers
{
public static class FlatBufferConstants
{
public const int FileIdentifierLength = 4;
}
}
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>FlatBuffers</id>
<version>1.0.0-alpha00003</version>
<authors>Google Inc</authors>
<description>A .NET port of Google Inc's FlatBuffers project.</description>
<language>en-US</language>
<projectUrl>https://github.com/evolutional/flatbuffers</projectUrl>
<licenseUrl>http://www.apache.org/licenses/LICENSE-2.0</licenseUrl>
</metadata>
</package>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{28C00774-1E73-4A75-AD8F-844CD21A064D}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>FlatBuffers</RootNamespace>
<AssemblyName>FlatBuffers</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="ByteBuffer.cs" />
<Compile Include="FlatBufferBuilder.cs" />
<Compile Include="FlatBufferConstants.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Struct.cs" />
<Compile Include="Table.cs" />
</ItemGroup>
<ItemGroup>
<None Include="FlatBuffers.1.0.0.nuspec" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FlatBuffers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlatBuffers")]
[assembly: AssemblyCopyright("Copyright © 2014 Google Inc")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91c32e64-ef20-47df-9c9f-cec9207bc6df")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace FlatBuffers
{
/// <summary>
/// All structs in the generated code derive from this class, and add their own accessors.
/// </summary>
public abstract class Struct
{
protected int bb_pos;
protected ByteBuffer bb;
}
}
\ No newline at end of file
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace FlatBuffers
{
/// <summary>
/// All tables in the generated code derive from this class, and add their own accessors.
/// </summary>
public abstract class Table
{
protected int bb_pos;
protected ByteBuffer bb;
// Look up a field in the vtable, return an offset into the object, or 0 if the field is not
// present.
protected int __offset(int vtableOffset)
{
int vtable = bb_pos - bb.GetInt(bb_pos);
return vtableOffset < bb.GetShort(vtable) ? bb.GetShort(vtable + vtableOffset) : 0;
}
// Retrieve the relative offset stored at "offset"
protected int __indirect(int offset)
{
return offset + bb.GetInt(offset);
}
// Create a .NET String from UTF-8 data stored inside the flatbuffer.
protected string __string(int offset)
{
offset += bb.GetInt(offset);
var len = bb.GetInt(offset);
var startPos = offset + sizeof(int);
return Encoding.UTF8.GetString(bb.Data, startPos , len);
}
// Get the length of a vector whose offset is stored at "offset" in this object.
protected int __vector_len(int offset)
{
offset += bb_pos;
offset += bb.GetInt(offset);
return bb.GetInt(offset);
}
// Get the start of data of a vector whose offset is stored at "offset" in this object.
protected int __vector(int offset)
{
offset += bb_pos;
return offset + bb.GetInt(offset) + sizeof(int); // data starts after the length
}
// Initialize any Table-derived type to point to the union at the given offset.
protected Table __union(Table t, int offset)
{
offset += bb_pos;
t.bb_pos = offset + bb.GetInt(offset);
t.bb = bb;
return t;
}
protected static bool __has_identifier(ByteBuffer bb, int offset, string ident)
{
if (ident.Length != FlatBufferConstants.FileIdentifierLength)
throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident");
for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++)
{
if (ident[i] != (char)bb.Get(offset + sizeof(int) + i)) return false;
}
return true;
}
}
}
...@@ -76,6 +76,8 @@ const Generator generators[] = { ...@@ -76,6 +76,8 @@ const Generator generators[] = {
"Generate Go files for tables/structs" }, "Generate Go files for tables/structs" },
{ flatbuffers::GenerateJava, "j", "Java", { flatbuffers::GenerateJava, "j", "Java",
"Generate Java classes for tables/structs" }, "Generate Java classes for tables/structs" },
{ flatbuffers::GenerateCSharp, "n", "C#",
"Generate C# classes for tables/structs" }
}; };
const char *program_name = NULL; const char *program_name = NULL;
......
This diff is collapsed.
File mode changed from 100755 to 100644
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FlatBuffers.Test
{
public class AssertFailedException : Exception
{
private readonly object _expected;
private readonly object _actual;
public AssertFailedException(object expected, object actual)
{
_expected = expected;
_actual = actual;
}
public override string Message
{
get { return string.Format("Expected {0} but saw {1}", _expected, _actual); }
}
}
public class AssertUnexpectedThrowException : Exception
{
private readonly object _expected;
public AssertUnexpectedThrowException(object expected)
{
_expected = expected;
}
public override string Message
{
get { return string.Format("Expected exception of type {0}", _expected); }
}
}
public static class Assert
{
public static void AreEqual<T>(T expected, T actual)
{
if (!expected.Equals(actual))
{
throw new AssertFailedException(expected, actual);
}
}
public static void IsTrue(bool value)
{
if (!value)
{
throw new AssertFailedException(true, value);
}
}
public static void Throws<T>(Action action) where T : Exception
{
var caught = false;
try
{
action();
}
catch (T ex)
{
caught = true;
}
if (!caught)
{
throw new AssertUnexpectedThrowException(typeof (T));
}
}
}
}
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace FlatBuffers.Test
{
public class ByteBufferTests
{
public void ByteBuffer_Length_MatchesBufferLength()
{
var buffer = new byte[1000];
var uut = new ByteBuffer(buffer);
Assert.AreEqual(buffer.Length, uut.Length);
}
public void ByteBuffer_PutBytePopulatesBufferAtZeroOffset()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
uut.PutByte(0, (byte)99);
Assert.AreEqual((byte)99, buffer[0]);
}
public void ByteBuffer_PutByteCannotPutAtOffsetPastLength()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutByte(1, 99));
}
public void ByteBuffer_PutShortPopulatesBufferCorrectly()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
uut.PutShort(0, (short)1);
// Ensure Endianness was written correctly
Assert.AreEqual((byte)1, buffer[0]);
Assert.AreEqual((byte)0, buffer[1]);
}
public void ByteBuffer_PutShortCannotPutAtOffsetPastLength()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutShort(2, 99));
}
public void ByteBuffer_PutShortChecksLength()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutShort(0, 99));
}
public void ByteBuffer_PutShortChecksLengthAndOffset()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutShort(1, 99));
}
public void ByteBuffer_PutIntPopulatesBufferCorrectly()
{
var buffer = new byte[4];
var uut = new ByteBuffer(buffer);
uut.PutInt(0, 0x0A0B0C0D);
// Ensure Endianness was written correctly
Assert.AreEqual(0x0D, buffer[0]);
Assert.AreEqual(0x0C, buffer[1]);
Assert.AreEqual(0x0B, buffer[2]);
Assert.AreEqual(0x0A, buffer[3]);
}
public void ByteBuffer_PutIntCannotPutAtOffsetPastLength()
{
var buffer = new byte[4];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutInt(2, 0x0A0B0C0D));
}
public void ByteBuffer_PutIntChecksLength()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutInt(0, 0x0A0B0C0D));
}
public void ByteBuffer_PutIntChecksLengthAndOffset()
{
var buffer = new byte[4];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutInt(2, 0x0A0B0C0D));
}
public void ByteBuffer_PutLongPopulatesBufferCorrectly()
{
var buffer = new byte[8];
var uut = new ByteBuffer(buffer);
uut.PutLong(0, 0x010203040A0B0C0D);
// Ensure Endianness was written correctly
Assert.AreEqual(0x0D, buffer[0]);
Assert.AreEqual(0x0C, buffer[1]);
Assert.AreEqual(0x0B, buffer[2]);
Assert.AreEqual(0x0A, buffer[3]);
Assert.AreEqual(0x04, buffer[4]);
Assert.AreEqual(0x03, buffer[5]);
Assert.AreEqual(0x02, buffer[6]);
Assert.AreEqual(0x01, buffer[7]);
}
public void ByteBuffer_PutLongCannotPutAtOffsetPastLength()
{
var buffer = new byte[8];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutLong(2, 0x010203040A0B0C0D));
}
public void ByteBuffer_PutLongChecksLength()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutLong(0, 0x010203040A0B0C0D));
}
public void ByteBuffer_PutLongChecksLengthAndOffset()
{
var buffer = new byte[8];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.PutLong(2, 0x010203040A0B0C0D));
}
public void ByteBuffer_GetByteReturnsCorrectData()
{
var buffer = new byte[1];
buffer[0] = 99;
var uut = new ByteBuffer(buffer);
Assert.AreEqual((byte)99, uut.Get(0));
}
public void ByteBuffer_GetByteChecksOffset()
{
var buffer = new byte[1];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(()=>uut.Get(1));
}
public void ByteBuffer_GetShortReturnsCorrectData()
{
var buffer = new byte[2];
buffer[0] = 1;
buffer[1] = 0;
var uut = new ByteBuffer(buffer);
Assert.AreEqual(1, uut.GetShort(0));
}
public void ByteBuffer_GetShortChecksOffset()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetShort(2));
}
public void ByteBuffer_GetShortChecksLength()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetShort(1));
}
public void ByteBuffer_GetIntReturnsCorrectData()
{
var buffer = new byte[4];
buffer[0] = 0x0D;
buffer[1] = 0x0C;
buffer[2] = 0x0B;
buffer[3] = 0x0A;
var uut = new ByteBuffer(buffer);
Assert.AreEqual(0x0A0B0C0D, uut.GetInt(0));
}
public void ByteBuffer_GetIntChecksOffset()
{
var buffer = new byte[4];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetInt(4));
}
public void ByteBuffer_GetIntChecksLength()
{
var buffer = new byte[2];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetInt(0));
}
public void ByteBuffer_GetLongReturnsCorrectData()
{
var buffer = new byte[8];
buffer[0] = 0x0D;
buffer[1] = 0x0C;
buffer[2] = 0x0B;
buffer[3] = 0x0A;
buffer[4] = 0x04;
buffer[5] = 0x03;
buffer[6] = 0x02;
buffer[7] = 0x01;
var uut = new ByteBuffer(buffer);
Assert.AreEqual(0x010203040A0B0C0D, uut.GetLong(0));
}
public void ByteBuffer_GetLongChecksOffset()
{
var buffer = new byte[8];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetLong(8));
}
public void ByteBuffer_GetLongChecksLength()
{
var buffer = new byte[7];
var uut = new ByteBuffer(buffer);
Assert.Throws<ArgumentOutOfRangeException>(() => uut.GetLong(0));
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9DB0B5E7-757E-4BD1-A5F6-279390331254}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>FlatBuffers.Test</RootNamespace>
<AssemblyName>FlatBuffers.Test</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\MyGame\Example\Any.cs">
<Link>MyGame\Example\Any.cs</Link>
</Compile>
<Compile Include="..\MyGame\Example\Color.cs">
<Link>MyGame\Example\Color.cs</Link>
</Compile>
<Compile Include="..\MyGame\Example\Monster.cs">
<Link>MyGame\Example\Monster.cs</Link>
</Compile>
<Compile Include="..\MyGame\Example\Test.cs">
<Link>MyGame\Example\Test.cs</Link>
</Compile>
<Compile Include="..\MyGame\Example\Vec3.cs">
<Link>MyGame\Example\Vec3.cs</Link>
</Compile>
<Compile Include="Assert.cs" />
<Compile Include="ByteBufferTests.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="FlatBuffersExampleTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\net\FlatBuffers\FlatBuffers.csproj">
<Project>{28C00774-1E73-4A75-AD8F-844CD21A064D}</Project>
<Name>FlatBuffers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="..\monsterdata_test.bin">
<Link>Resources\monsterdata_test.bin</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.IO;
using MyGame.Example;
namespace FlatBuffers.Test
{
public class FlatBuffersExampleTests
{
public void RunTests()
{
CanCreateNewFlatBufferFromScratch();
CanReadCppGeneratedWireFile();
}
public void CanCreateNewFlatBufferFromScratch()
{
// Second, let's create a FlatBuffer from scratch in C#, and test it also.
// We use an initial size of 1 to exercise the reallocation algorithm,
// normally a size larger than the typical FlatBuffer you generate would be
// better for performance.
var fbb = new FlatBufferBuilder(1);
// We set up the same values as monsterdata.json:
var str = fbb.CreateString("MyMonster");
var test1 = fbb.CreateString("test1");
var test2 = fbb.CreateString("test2");
Monster.StartInventoryVector(fbb, 5);
for (int i = 4; i >= 0; i--)
{
fbb.AddByte((byte)i);
}
var inv = fbb.EndVector();
Monster.StartMonster(fbb);
Monster.AddHp(fbb, (short)20);
var mon2 = Monster.EndMonster(fbb);
Monster.StartTest4Vector(fbb, 2);
MyGame.Example.Test.CreateTest(fbb, (short)10, (byte)20);
MyGame.Example.Test.CreateTest(fbb, (short)30, (byte)40);
var test4 = fbb.EndVector();
Monster.StartTestarrayofstringVector(fbb, 2);
fbb.AddOffset(test2);
fbb.AddOffset(test1);
var testArrayOfString = fbb.EndVector();
Monster.StartMonster(fbb);
Monster.AddPos(fbb, Vec3.CreateVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
(byte)4, (short)5, (byte)6));
Monster.AddHp(fbb, (short)80);
Monster.AddName(fbb, str);
Monster.AddInventory(fbb, inv);
Monster.AddTestType(fbb, (byte)1);
Monster.AddTest(fbb, mon2);
Monster.AddTest4(fbb, test4);
Monster.AddTestarrayofstring(fbb, testArrayOfString);
var mon = Monster.EndMonster(fbb);
fbb.Finish(mon);
// Dump to output directory so we can inspect later, if needed
using (var ms= new MemoryStream(fbb.Data.Data, fbb.DataStart, fbb.Offset))
{
var data = ms.ToArray();
File.WriteAllBytes(@"Resources/monsterdata_cstest.bin",data);
}
// Now assert the buffer
TestBuffer(fbb.Data, fbb.DataStart);
}
private void TestBuffer(ByteBuffer bb, int start)
{
var monster = Monster.GetRootAsMonster(bb, start);
Assert.AreEqual(80, monster.Hp());
Assert.AreEqual(150, monster.Mana());
Assert.AreEqual("MyMonster", monster.Name());
var pos = monster.Pos();
Assert.AreEqual(1.0f, pos.X());
Assert.AreEqual(2.0f, pos.Y());
Assert.AreEqual(3.0f, pos.Z());
Assert.AreEqual(3.0f, pos.Test1());
Assert.AreEqual((byte)4, pos.Test2());
var t = pos.Test3();
Assert.AreEqual((short)5, t.A());
Assert.AreEqual((byte)6, t.B());
Assert.AreEqual((byte)Any.Monster, monster.TestType());
var monster2 = new Monster();
Assert.IsTrue(monster.Test(monster2) != null);
Assert.AreEqual(20, monster2.Hp());
Assert.AreEqual(5, monster.InventoryLength());
var invsum = 0;
for (var i = 0; i < monster.InventoryLength(); i++)
{
invsum += monster.Inventory(i);
}
Assert.AreEqual(10, invsum);
var test0 = monster.Test4(0);
var test1 = monster.Test4(1);
Assert.AreEqual(2, monster.Test4Length());
Assert.AreEqual(100, test0.A() + test0.B() + test1.A() + test1.B());
Assert.AreEqual(2, monster.TestarrayofstringLength());
Assert.AreEqual("test1", monster.Testarrayofstring(0));
Assert.AreEqual("test2", monster.Testarrayofstring(1));
}
public void CanReadCppGeneratedWireFile()
{
var data = File.ReadAllBytes(@"Resources/monsterdata_test.bin");
var bb = new ByteBuffer(data);
TestBuffer(bb, 0);
}
}
}
using System;
using System.Linq;
using System.Reflection;
namespace FlatBuffers.Test
{
static class Program
{
public static int Main(string[] args)
{
var tests = new FlatBuffersExampleTests();
try
{
tests.RunTests();
}
catch (Exception ex)
{
Console.WriteLine("FlatBuffersExampleTests FAILED - {0}", ex.GetBaseException());
return -1;
}
// Run ByteBuffers Tests
var testClass = new ByteBufferTests();
var methods = testClass.GetType().GetMethods(BindingFlags.Public |
BindingFlags.Instance)
.Where(m => m.Name.StartsWith("ByteBuffer_"));
foreach (var method in methods)
{
try
{
method.Invoke(testClass, new object[] { });
}
catch (Exception ex)
{
Console.WriteLine("ByteBufferTests FAILED when invoking {0} with error {1}",
method.Name, ex.GetBaseException());
return -1;
}
}
return 0;
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FlatBuffers.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FlatBuffers.Test")]
[assembly: AssemblyCopyright("Copyright © 2014 Google Inc")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a1d58a51-3e74-4ae9-aac7-5a399c9eed1a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
File mode changed from 100755 to 100644
// automatically generated, do not modify
namespace MyGame.Example
{
using FlatBuffers;
public class Any
{
public static byte NONE = 0;
public static byte Monster = 1;
};
}
// automatically generated, do not modify
namespace MyGame.Example
{
using FlatBuffers;
public class Color
{
public static byte Red = 1;
public static byte Green = 2;
public static byte Blue = 8;
};
}
// automatically generated, do not modify
namespace MyGame.Example
{
using FlatBuffers;
public class Monster : Table {
public static Monster GetRootAsMonster(ByteBuffer _bb, int offset) { return (new Monster()).__init(_bb.GetInt(offset) + offset, _bb); }
public static bool MonsterBufferHasIdentifier(ByteBuffer _bb, int offset) { return __has_identifier(_bb, offset, "MONS"); }
public Monster __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }
public Vec3 Pos() { return Pos(new Vec3()); }
public Vec3 Pos(Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__init(o + bb_pos, bb) : null; }
public short Mana() { int o = __offset(6); return o != 0 ? bb.GetShort(o + bb_pos) : (short)150; }
public short Hp() { int o = __offset(8); return o != 0 ? bb.GetShort(o + bb_pos) : (short)100; }
public string Name() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; }
public byte Inventory(int j) { int o = __offset(14); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; }
public int InventoryLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; }
public byte Color() { int o = __offset(16); return o != 0 ? bb.Get(o + bb_pos) : (byte)8; }
public byte TestType() { int o = __offset(18); return o != 0 ? bb.Get(o + bb_pos) : (byte)0; }
public Table Test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o) : null; }
public Test Test4(int j) { return Test4(new Test(), j); }
public Test Test4(Test obj, int j) { int o = __offset(22); return o != 0 ? obj.__init(__vector(o) + j * 4, bb) : null; }
public int Test4Length() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; }
public string Testarrayofstring(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int TestarrayofstringLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; }
/* an example documentation comment: this will end up in the generated code multiline too */
public Monster Testarrayoftables(int j) { return Testarrayoftables(new Monster(), j); }
public Monster Testarrayoftables(Monster obj, int j) { int o = __offset(26); return o != 0 ? obj.__init(__indirect(__vector(o) + j * 4), bb) : null; }
public int TestarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; }
public Monster Enemy() { return Enemy(new Monster()); }
public Monster Enemy(Monster obj) { int o = __offset(28); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; }
public byte Testnestedflatbuffer(int j) { int o = __offset(30); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; }
public int TestnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; }
public Monster Testempty() { return Testempty(new Monster()); }
public Monster Testempty(Monster obj) { int o = __offset(32); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; }
public static void StartMonster(FlatBufferBuilder builder) { builder.StartObject(15); }
public static void AddPos(FlatBufferBuilder builder, int posOffset) { builder.AddStruct(0, posOffset, 0); }
public static void AddMana(FlatBufferBuilder builder, short mana) { builder.AddShort(1, mana, 150); }
public static void AddHp(FlatBufferBuilder builder, short hp) { builder.AddShort(2, hp, 100); }
public static void AddName(FlatBufferBuilder builder, int nameOffset) { builder.AddOffset(3, nameOffset, 0); }
public static void AddInventory(FlatBufferBuilder builder, int inventoryOffset) { builder.AddOffset(5, inventoryOffset, 0); }
public static void StartInventoryVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); }
public static void AddColor(FlatBufferBuilder builder, byte color) { builder.AddByte(6, color, 8); }
public static void AddTestType(FlatBufferBuilder builder, byte testType) { builder.AddByte(7, testType, 0); }
public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); }
public static void AddTest4(FlatBufferBuilder builder, int test4Offset) { builder.AddOffset(9, test4Offset, 0); }
public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); }
public static void AddTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset, 0); }
public static void StartTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
public static void AddTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset, 0); }
public static void StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
public static void AddEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.AddOffset(12, enemyOffset, 0); }
public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset, 0); }
public static void StartTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); }
public static void AddTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.AddOffset(14, testemptyOffset, 0); }
public static int EndMonster(FlatBufferBuilder builder) { return builder.EndObject(); }
public static void FinishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.Finish(offset, "MONS"); }
};
}
// automatically generated, do not modify
namespace MyGame.Example
{
using FlatBuffers;
public class Test : Struct {
public Test __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }
public short A() { return bb.GetShort(bb_pos + 0); }
public byte B() { return bb.Get(bb_pos + 2); }
public static int CreateTest(FlatBufferBuilder builder, short A, byte B) {
builder.Prep(2, 4);
builder.Pad(1);
builder.PutByte(B);
builder.PutShort(A);
return builder.Offset;
}
};
}
// automatically generated, do not modify
namespace MyGame.Example
{
using FlatBuffers;
public class Vec3 : Struct {
public Vec3 __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }
public float X() { return bb.GetFloat(bb_pos + 0); }
public float Y() { return bb.GetFloat(bb_pos + 4); }
public float Z() { return bb.GetFloat(bb_pos + 8); }
public double Test1() { return bb.GetDouble(bb_pos + 16); }
public byte Test2() { return bb.Get(bb_pos + 24); }
public Test Test3() { return Test3(new Test()); }
public Test Test3(Test obj) { return obj.__init(bb_pos + 26, bb); }
public static int CreateVec3(FlatBufferBuilder builder, float X, float Y, float Z, double Test1, byte Test2, short Test_A, byte Test_B) {
builder.Prep(16, 32);
builder.Pad(2);
builder.Prep(2, 4);
builder.Pad(1);
builder.PutByte(Test_B);
builder.PutShort(Test_A);
builder.Pad(1);
builder.PutByte(Test2);
builder.PutDouble(Test1);
builder.Pad(4);
builder.PutFloat(Z);
builder.PutFloat(Y);
builder.PutFloat(X);
return builder.Offset;
}
};
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment