From 820a7f277f9591adec72408c7b05a103397626f2 Mon Sep 17 00:00:00 2001 From: Derek Bailey Date: Mon, 10 Feb 2025 20:13:22 -0800 Subject: [PATCH] Remove old documentation --- docs-old/README.md | 3 - docs-old/footer.html | 14 - docs-old/header.html | 62 - docs-old/images/fpl_logo_small.png | Bin 5073 -> 0 bytes docs-old/images/ftv2mnode.png | Bin 1048 -> 0 bytes docs-old/images/ftv2pnode.png | Bin 1045 -> 0 bytes docs-old/source/Benchmarks.md | 63 - docs-old/source/Building.md | 134 - docs-old/source/CONTRIBUTING.md | 1 - docs-old/source/CUsage.md | 224 -- docs-old/source/Compiler.md | 281 -- docs-old/source/CppUsage.md | 639 --- docs-old/source/CsharpUsage.md | 265 -- docs-old/source/DartUsage.md | 131 - docs-old/source/FlatBuffers.md | 188 - docs-old/source/FlexBuffers.md | 204 - docs-old/source/GoApi.md | 26 - docs-old/source/GoApi_generated.txt | 125 - docs-old/source/GoUsage.md | 99 - docs-old/source/Grammar.md | 74 - docs-old/source/IntermediateRepresentation.md | 35 - docs-old/source/Internals.md | 468 --- docs-old/source/JavaScriptUsage.md | 93 - docs-old/source/JavaUsage.md | 114 - docs-old/source/KotlinUsage.md | 84 - docs-old/source/LobsterUsage.md | 85 - docs-old/source/LuaUsage.md | 81 - docs-old/source/PHPUsage.md | 89 - docs-old/source/PythonUsage.md | 100 - docs-old/source/README_TO_GENERATE_DOCS.md | 32 - docs-old/source/RustUsage.md | 186 - docs-old/source/Schemas.md | 685 ---- docs-old/source/Support.md | 57 - docs-old/source/SwiftUsage.md | 97 - docs-old/source/Tutorial.md | 3563 ----------------- docs-old/source/TypeScriptUsage.md | 96 - docs-old/source/WhitePaper.md | 128 - docs-old/source/doxyfile | 2375 ----------- docs-old/source/doxygen_layout.xml | 254 -- docs-old/source/gRPC/CppUsage.md | 29 - docs-old/source/groups | 23 - docs-old/source/style.css | 396 -- docs/overrides/404.html | 3 +- docs/overrides/main.html | 5 - 44 files changed, 1 insertion(+), 11610 deletions(-) delete mode 100644 docs-old/README.md delete mode 100644 docs-old/footer.html delete mode 100644 docs-old/header.html delete mode 100644 docs-old/images/fpl_logo_small.png delete mode 100644 docs-old/images/ftv2mnode.png delete mode 100644 docs-old/images/ftv2pnode.png delete mode 100644 docs-old/source/Benchmarks.md delete mode 100644 docs-old/source/Building.md delete mode 120000 docs-old/source/CONTRIBUTING.md delete mode 100644 docs-old/source/CUsage.md delete mode 100644 docs-old/source/Compiler.md delete mode 100644 docs-old/source/CppUsage.md delete mode 100644 docs-old/source/CsharpUsage.md delete mode 100644 docs-old/source/DartUsage.md delete mode 100644 docs-old/source/FlatBuffers.md delete mode 100644 docs-old/source/FlexBuffers.md delete mode 100644 docs-old/source/GoApi.md delete mode 100644 docs-old/source/GoApi_generated.txt delete mode 100644 docs-old/source/GoUsage.md delete mode 100644 docs-old/source/Grammar.md delete mode 100644 docs-old/source/IntermediateRepresentation.md delete mode 100644 docs-old/source/Internals.md delete mode 100644 docs-old/source/JavaScriptUsage.md delete mode 100644 docs-old/source/JavaUsage.md delete mode 100644 docs-old/source/KotlinUsage.md delete mode 100644 docs-old/source/LobsterUsage.md delete mode 100644 docs-old/source/LuaUsage.md delete mode 100644 docs-old/source/PHPUsage.md delete mode 100644 docs-old/source/PythonUsage.md delete mode 100644 docs-old/source/README_TO_GENERATE_DOCS.md delete mode 100644 docs-old/source/RustUsage.md delete mode 100644 docs-old/source/Schemas.md delete mode 100644 docs-old/source/Support.md delete mode 100644 docs-old/source/SwiftUsage.md delete mode 100644 docs-old/source/Tutorial.md delete mode 100644 docs-old/source/TypeScriptUsage.md delete mode 100644 docs-old/source/WhitePaper.md delete mode 100644 docs-old/source/doxyfile delete mode 100644 docs-old/source/doxygen_layout.xml delete mode 100644 docs-old/source/gRPC/CppUsage.md delete mode 100644 docs-old/source/groups delete mode 100644 docs-old/source/style.css diff --git a/docs-old/README.md b/docs-old/README.md deleted file mode 100644 index 61acb41d829..00000000000 --- a/docs-old/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This is the source of the old docs that are being replaced. They are served -from the `gh-pages-old` branch, while the new documentations (source in docs/) -is served from the `gh-pages` branch. \ No newline at end of file diff --git a/docs-old/footer.html b/docs-old/footer.html deleted file mode 100644 index 42bc5f2b903..00000000000 --- a/docs-old/footer.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - diff --git a/docs-old/header.html b/docs-old/header.html deleted file mode 100644 index 0266e7c4f30..00000000000 --- a/docs-old/header.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - -$projectname: $title -$title - - - -$treeview -$search -$mathjax - - -$extrastylesheet - - -
- - -
- - - - - - - - - - - - - - - - - - - - - - -
-
$projectname -  $projectnumber -
-
- An open source project by FPL. -
-
$projectbrief
-
-
$projectbrief
-
$searchbox
-
- - diff --git a/docs-old/images/fpl_logo_small.png b/docs-old/images/fpl_logo_small.png deleted file mode 100644 index 2c728f3b541184490702effdc4360c3f795cb1bd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5073 zcmY*-cQ_nQ*Y*;1t>~R#Mejt^)uNZIUV`WwtkpXaHA)0QunE!mA&A~qO|6fr{FH!tYiPu#=CEhm5eWzrVkbzqpXQ*9&1$X=!O;5iwygF~K{8 zpm(5~k8OaUn>WY5N&X*?ileu^m$QeDv%4GHUtU`~cV8a}82nf0zwO_7`Z&Y>zml8x zf6BTmQ26hTu&9uT@PE1QLgoH?WuRWpj(5s``Q=6B{)PNMzW?aR3I7%UU&;Kt(tmmH zN|gu73IF%lY|H+Qa%aiG%n+N8gYu?q6$kr5?!!Uw0%Mx zYnZ1?Ji@g$bobAEYwOu3@5`&G-#VGY0<9JJWjmahyiMHuh-f|lv+oe;eb&CN~IoPGTEh4}D4LCqAK4JN+43uht6$EWm;bz8G#75w-b z7&O}4{?JcXJL(kAtw%=^VGtGa#M;{0bTHo@zrTy-jd<2cz+3;XO$^J-4_UJ7Bcs#k z`G1)wva!F%j5A(dUL_ZZ$?&r9DsH39vLwze+<%A`kRnCB4okR4VW-(2*HceuHL^QN z4~)a6?ga%0Z!$$SwoNqPu57Hq)?H{_CtCYJLTo4)Bm<{uba`wxwh0~}X{m~e8qFY{ zId_X^p;OKCOf*oDEvjf!>4p!Nv>AKB-=Nd^CW%cZpvt%@LBPZNvpRqYt*Vbmja|w z%C^Ndk3PP037?mUn+>@?4h?<1Kf`M8NYLb%09U}sG96joFLA~x;auzn^>~a>ZLeovE+E?+4v8lXv$l9?nyn=bdkY!rFc%r* zAzMk|U-ndQomaF1BrBHqqeFdJulKMJ)Rlr(j^g^yZc#5Ark<}DjN+tV zO(`x62BW+Rfn=N6%%)c|{bPOviM`(*zTXhzd`Rt;2x$ggU+qOTZo6>U9B=7ILE8Wc zN%zV(QKu|n9cNeje_Ch~>S$N#SE*~!%mf6N+tF-=dALiy?(21n{n24H3ZJ$_H2E** zI~0$*^=&4}J^TpJeXRJWJ8Ito7W9bj1yrHp5BFZqcVfhAKv(Yq|G0a@ma5z+QQb}&QR8t~(K zs6RPCOmvILJjc?)?Dqh(G2~VugbR>Huw5D~%Cwa~U;Wj)ydJz@x9%&c`>&$lr&H!a zdA#Le&nDa)n4q$HRApZ+egR#mbB|Du-rH1=;tsdc%LVqX5xfY~ps-0@I)1n6N=J^d zOE>vBc*|%=6Y80z`B=P*_(2&^uONkCM1bmLOE70UkM^m`Lo=J)QFA0UtTPG5fVmuDrh3l38yf||g5n?Iwh%qj<%#_hn;rJ@{Zf#&dJLL)kBcMa(GiRUl*YFq0I!ov7|tuc_?%i3u7P zQ(*Ii!%r31#8K=0KfJVdRx(c4pW&%U-Z<%+_??_;7%EZxRk~-_a8BROOej-Nd4q`H zZr=5@u*g*jHf$%x1YGL^VBk33?ssKvREM#2F|C1IXeKlJe#xg)TNW#TUj<15MM~kr zX0F(3hxd&#INL#w03w`j(;}72e!c!T6_`Z_2f-lLn+Ney@kc!DNi6-ljOwpt!$;-i zU&bWu_E%a%E4X=QfT_iqJ4mdD@gd8%$sE>LGl~kKS0q7mO{! zgXsx(N@zY8?>kQ9Kk(R1pumPt&q_{?(GqxmsXJ>A8RF$#tDaB?Jfo>iHzB42`l*w%`|_rfKOM=# zUNfibrY};Zvqyto%(XsB8oHziko!i@{ANONs8(YZ%xNaIIl)Z%T$J{kZz4BaT$z4H zfXb?F4Euw~>W{Qxl9~G=1g4XM;QR$KsOwQypx;@L*ZxRH+?@LYDYP{@&5S*LF4`s8 z$Ecc$VQh;NYSJ;n?h{oqKk{K5VWA1DJ;9+=OQTZN>i0C?_#*BeB`8Auph6{VBEGh5 zsuM3U@p&{fzKG^0LL^)=R3eKWMOz#M(x&>%V!ElWEHfFrJ%i(KIZ#Kp9L^=Jz^er8 z&-oDEv0kuWH5Z{VU{K3Zm!Gxv&-_#Ixb;3+K4LwQLg3+sYq?aejLeeuE)GNR#)EURg+2|hVQ?zg*Qg9oG$_{# z(6?=2i~Q%Yz@_R)Qc3$p|3@N)n-`r2jp2e8QU#Rlq&o&tPv0>~cE8%<->)p7k|;4U zhsqND%Iy*&;Zd}F7*|@E@*3R|s+$zQFLm-D0zrl|*hJ!Lk?8bc+nlQpjW7oD#$}?| zVeSh^yoC-Bwx4SM@yl33-V3}wb$)@0Uwq30+6w**3U5cNGalO8R`!71@x%pbsL0OR z6^*mk)RRR2Y^$DgZ_X9-C@RpTTyJYn5qj;vNg!TW74itzOf6TBEr{JfzH;Xr$3CnO=#reslFm2WiXAx&HZt0zZ#H5j_%D99 z(6w>!Q|MTJ+ZnwNzWUKOeq}8Tmhr>AMYLv0um7w=KVA%E|I+=37MR>bIh!s8d}CX! z#hd^wu1ER*UY%xR{}Nqcy~slLByZMi-mA*F29tmm8TJZbx93NWbW!bk+cc=&7XO_*0@+<84fM*2R&*AIi~NdwT8I`4jl|tkZ8Wu z5`fM9B3gU)-uGRn3@KwpN^Z&nx=+CmsLoyj%RgOE3aX8JMHfuYPcD~{4AD7wmnv%vnT(nFJt@#P)P=gKAM`)+U#;f9SBgL#`<9CX6iJoSwE$-X$B`BrEb43$_ zm~g%swKm>eEVBZwdJIKrb29^6;%)h~%aIZ+GB*^;#cdH!t|;VA1S{RM3B`Dl+QT3Hx|=D3YHym5=D zaJTLg+}10>&A1oDbxG8ZB)i`pF=5JzqZZg}-9^n1$+e&hW6wpnoTt4o_Q@SqsypsxwP`?CPw z@@VPBACyNK8yt=ktZ5xbG%7LA*JCK(*>AmN<(D`bM;h+aO9oK;p|kyMkG(r0!;^ND zeEyI_lV_Vw8A#)o8?+1B>qS_`d^QbKuT2}fn6uNH@h74($G#~)-b^E~@a6EvevRE& zK^YI0hK^M7)D^=6s$(sKa%JBiymb>Z9B|mdSb?$#oam-T^ z@$}CLYqxCo(0;XhfqU|IgBraqySLNJXdeuHjfg@E8g>|#_TzmSKGE0{!@8Wr&rKuW z>=84SfmhAXI1tc5qX>z%@4&*SBnV)ycXoJsjpZi^_NRs1jvPtWg@8yq=>qIl(B46+ z0blAs;Cg(XNOE@#$0=RQLrS%L(k}BKQ2fwo#y9fvh%r!YVKvRSmiiS=2f?9f`%Kl( zLAb?TUUp24VDGCccFF$F&^797<752B{fTcY=FhrBRU|_hZ^c4sgjm*XWexVb82q5*1$S+)`@IgrLBv zky}xkwqijMH^eO$!^4nI#Eitk45>vUxR%SSgAU0LS0ySM;5QMM#7mj+FTQyqEG&mL z3Zi;f0xPjtHMgbU*k0b9{bvrNa$UjqOhq(;SiNUn-O~?cs2;p0)R5c}-#M6mz%!pa zWu{nT6&`VA=MbH&SpQ3V+WzhlDXNo6JR=!V?WxkLK;ZsWN=!VM;-pG->=mH`8H=ij zR`g2Gh5?bg^A>1)Cn7CqDhN->tWW|u2zW0tET}zFP)o_52g~Z@gax4F(|WPV+O`C% zZ-dX-qXq_&V{#B=B4+V3FNe(x-)VisRBnGx%H;%(77|`$=y;|v`Mb5?%>k@348scN zyO4%*s6k0Fs?`AhDi6lyRBXb;CDe=f^9tWPk6qx;h{qWS``k^`9p_)jSu0F>o&f=uNx+M2@?sHdh^*)fY$0n5h4xBd)A&*(+dy zJN2stCiWSf75_-2W)slFRV}WKN0IXJ`X=hR3#4@c0Pf$$8K zKA;B2G+N1`sM%Tv-|6x3Z?qkgM$$&{Q_?}@CZn|alw6tS({b*&1-tM0)X7s#(|H2Q z^2#0;u?ZrroSndHd*igG~rY!sd&-J|H{$;UyAFQXlcVrPOsTuvhPoY k814(#XmNDa1KD*tnEI!J2l(l zp#~2YuO8HcU=_g!+8(8XJqZP|f<1@`6%ntcH}O(u(_7H@p zL(ODSRvhAGL-R{6#_wn*W)nnD#4#m#0wR!uFO08ANN?BTWr)OAL@AAEj-r;&c5^FH*q^DL^IBp-0$t} zi091R`5Q6%DslASSoEj2vopLueaKngcvIYb(9qj%Xwj$ue u%E=eMtosWK3)I7}w>~vLx~F>EiPkYfcv|}QzO?9Z-)b_E5?;o}N`C-|)J}W= diff --git a/docs-old/images/ftv2pnode.png b/docs-old/images/ftv2pnode.png deleted file mode 100644 index f1aaad3786e39e12a1233ce00d96ab8b1018456a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1045 zcmaJ=O-$2J950!o0T-1-jL6|pLIR0v*FqU>n6RxwwpfB=i92vu*FIQf{jhy=g?Io% zA|x6=j%p$oFCIL2GSS4Z#Ds%*(YP4n!Gj(N7ctQUU&l5)IGen__ka2Qe*e$6IyrI1 z-_p@S5QIN5E~fB)1h4jk&G^6mu=6tBPM~-OO_?*OB-@aPsAdj=gf7p*6qMEZi|cTh zAbj0gI)gIOSwS&%O7<|6t6P{&5W^#`B`b3ffgGIGj4-+R^f?JMHB6r8q@ZNQU|t(v zu;J9gL|R#xQ+SmeISqzg0So95$-vbMh9kIPvZ5>Cvv*CCpaMa2VRAR9j5G;irVRl{ zaRDXBG9biL3^%|t%qhSInSPoH(kvff7-1kJFoU4_k=UE9&Il=Stm+F}VKR@9CD3%K zRH91#lxfe>4A1j)kfm8RfDr*_-axV&Fr4n1f(RYO)-0r%2JjT+oLNL+5=Xk5f^OAi z4X0WrTrk>|Et;W%UP?8fB>f+%>vgn)QgAQce+oP4c?;4h=$J)Y!Ht{g_FP#)%!V>D z?X+nYYE_)fo5*zXrUha#&@0J`W_WgAg&;{n!f=pmC@>+0Ni0EWnkukyR*bSkgG@Yx ziyh~N_;^3h4aFin7ZXDvw#F4rrKm##)wt>&H`I{p&4O-W&my$7OHduNO&wHn7PQ8( z3^dfMa@EGMa1FUM4upr?@*dbqLX4!{Pr2Va zJ0rfH#nq)~@B(qCDVa=eFO~1M9q%Q!+Sj^HE@p1E(La4##kH;n%ZIY!#Q3PcoceGK zY& diff --git a/docs-old/source/Building.md b/docs-old/source/Building.md deleted file mode 100644 index 1315467c5e8..00000000000 --- a/docs-old/source/Building.md +++ /dev/null @@ -1,134 +0,0 @@ -Building {#flatbuffers_guide_building} -======== - -## Building with CMake - -The distribution comes with a `cmake` file that should allow -you to build project/make files for any platform. For details on `cmake`, see -. In brief, depending on your platform, use one of -e.g.: - - cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release - cmake -G "Visual Studio 10" -DCMAKE_BUILD_TYPE=Release - cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release - -Then, build as normal for your platform. This should result in a `flatc` -executable, essential for the next steps. -Note that to use clang instead of gcc, you may need to set up your environment -variables, e.g. -`CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix Makefiles"`. - -Optionally, run the `flattests` executable from the root `flatbuffers/` -directory to ensure everything is working correctly on your system. If this -fails, please contact us! - -Building should also produce two sample executables, `flatsamplebinary` and -`flatsampletext`, see the corresponding `.cpp` files in the -`flatbuffers/samples` directory. - -*Note that you MUST be in the root of the FlatBuffers distribution when you -run 'flattests' or `flatsampletext`, or it will fail to load its files.* - -### Make all warnings into errors - -By default all Flatbuffers `cmake` targets are **not** built with the `-Werror` -(or `/WX` for MSVC) flag that treats any warning as an error. This allows more -flexibility for users of Flatbuffers to use newer compilers and toolsets that -may add new warnings that would cause a build failure. - -To enable a stricter build that does treat warnings as errors, set the -`FLATBUFFERS_STRICT_MODE` `cmake` compliation flag to `ON`. - -``` -cmake . -DFLATBUFFERS_STRICT_MODE=ON -``` - -Our CI builds run with strict mode on, ensuring the code that is committed to -the project is as portable and warning free as possible. Thus developers -contributing to the project should enable strict mode locally before making a -PR. - -## Building with VCPKG - -You can download and install flatbuffers using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager: - - git clone https://github.com/Microsoft/vcpkg.git - cd vcpkg - ./bootstrap-vcpkg.sh - ./vcpkg integrate install - ./vcpkg install flatbuffers - -The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors. -If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. - -## Downloading binaries -You can download the binaries from the -[GitHub release page](https://github.com/google/flatbuffers/releases). - -We generate [SLSA3 signatures](slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries: -1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation) -1. Download the file named `attestation.intoto.jsonl` from the GitHub release -1. Run: -```shell -$ slsa-verifier -artifact-path -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag - PASSED: Verified SLSA provenance -``` - -## Building for Android - -There is a `flatbuffers/android` directory that contains all you need to build -the test executable on android (use the included `build_apk.sh` script, or use -`ndk_build` / `adb` etc. as usual). Upon running, it will output to the log -if tests succeeded or not. - -You may also run an android sample from inside the `flatbuffers/samples`, by -running the `android_sample.sh` script. Optionally, you may go to the -`flatbuffers/samples/android` folder and build the sample with the -`build_apk.sh` script or `ndk_build` / `adb` etc. - -## Using FlatBuffers in your own projects - -For C++, there is usually no runtime to compile, as the code consists of a -single header, `include/flatbuffers/flatbuffers.h`. You should add the -`include` folder to your include paths. If you wish to be -able to load schemas and/or parse text into binary buffers at runtime, -you additionally need the other headers in `include/flatbuffers`. You must -also compile/link `src/idl_parser.cpp` (and `src/idl_gen_text.cpp` if you -also want to be able convert binary to text). - -To see how to include FlatBuffers in any of our supported languages, please -view the [Tutorial](@ref flatbuffers_guide_tutorial) and select your appropriate -language using the radio buttons. - -### Using in CMake-based projects -If you want to use FlatBuffers in a project which already uses CMake, then a more -robust and flexible approach is to build FlatBuffers as part of that project directly. -This is done by making the FlatBuffers source code available to the main build -and adding it using CMake's `add_subdirectory()` command. This has the -significant advantage that the same compiler and linker settings are used -between FlatBuffers and the rest of your project, so issues associated with using -incompatible libraries (eg debug/release), etc. are avoided. This is -particularly useful on Windows. - -Suppose you put FlatBuffers source code in directory `${FLATBUFFERS_SRC_DIR}`. -To build it as part of your project, add following code to your `CMakeLists.txt` file: -```cmake -# Add FlatBuffers directly to our build. This defines the `flatbuffers` target. -add_subdirectory(${FLATBUFFERS_SRC_DIR} - ${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-build - EXCLUDE_FROM_ALL) - -# Now simply link against flatbuffers as needed to your already declared target. -# The flatbuffers target carry header search path automatically if CMake > 2.8.11. -target_link_libraries(own_project_target PRIVATE flatbuffers) -``` -When build your project the `flatbuffers` library will be compiled and linked -to a target as part of your project. - -#### Override default depth limit of nested objects -To override [the depth limit of recursion](@ref flatbuffers_guide_use_cpp), -add this directive: -```cmake -set(FLATBUFFERS_MAX_PARSING_DEPTH 16) -``` -to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line. diff --git a/docs-old/source/CONTRIBUTING.md b/docs-old/source/CONTRIBUTING.md deleted file mode 120000 index f939e75f21a..00000000000 --- a/docs-old/source/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -../../CONTRIBUTING.md \ No newline at end of file diff --git a/docs-old/source/CUsage.md b/docs-old/source/CUsage.md deleted file mode 100644 index bd1ec159d21..00000000000 --- a/docs-old/source/CUsage.md +++ /dev/null @@ -1,224 +0,0 @@ -Use in C {#flatbuffers_guide_use_c} -========== - -The C language binding exists in a separate project named [FlatCC](https://github.com/dvidelabs/flatcc). - -The `flatcc` C schema compiler can generate code offline as well as -online via a C library. It can also generate buffer verifiers and fast -JSON parsers, printers. - -Great care has been taken to ensure compatibility with the main `flatc` -project. - -## General Documention - -- [Tutorial](@ref flatbuffers_guide_tutorial) - select C as language - when scrolling down -- [FlatCC Guide](https://github.com/dvidelabs/flatcc#flatcc-flatbuffers-in-c-for-c) -- [The C Builder Interface](https://github.com/dvidelabs/flatcc/blob/master/doc/builder.md#the-builder-interface) -- [The Monster Sample in C](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c) -- [GitHub](https://github.com/dvidelabs/flatcc) - - -## Supported Platforms - -- Ubuntu (clang / gcc, ninja / gnu make) -- OS-X (clang / gcc, ninja / gnu make) -- Windows MSVC 2010, 2013, 2015 - -CI builds recent versions of gcc, clang and MSVC on OS-X, Ubuntu, and -Windows, and occasionally older compiler versions. See main project [Status](https://github.com/dvidelabs/flatcc#status). - -Other platforms may well work, including Centos, but are not tested -regularly. - -The monster sample project was specifically written for C99 in order to -follow the C++ version and for that reason it will not work with MSVC -2010. - -## Modular Object Creation - -In the tutorial we used the call `Monster_create_as_root` to create the -root buffer object since this is easier in simple use cases. Sometimes -we need more modularity so we can reuse a function to create nested -tables and root tables the same way. For this we need the -`flatcc_builder_buffer_create_call`. It is best to keep `flatcc_builder` -calls isolated at the top driver level, so we get: - -
-~~~{.c} - ns(Monster_ref_t) create_orc(flatcc_builder_t *B) - { - // ... same as in the tutorial. - return s(Monster_create(B, ...)); - } - - void create_monster_buffer() - { - uint8_t *buf; - size_t size; - flatcc_builder_t builder, *B; - - // Initialize the builder object. - B = &builder; - flatcc_builder_init(B); - // Only use `buffer_create` without `create/start/end_as_root`. - flatcc_builder_buffer_create(create_orc(B)); - // Allocate and copy buffer to user memory. - buf = flatcc_builder_finalize_buffer(B, &size); - // ... write the buffer to disk or network, or something. - - free(buf); - flatcc_builder_clear(B); - } -~~~ -
- -The same principle applies with `start/end` vs `start/end_as_root` in -the top-down approach. - - -## Top Down Example - -The tutorial uses a bottom up approach. In C it is also possible to use -a top-down approach by starting and ending objects nested within each -other. In the tutorial there is no deep nesting, so the difference is -limited, but it shows the idea: - -
-
-~~~{.c} - uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - size_t treasure_count = c_vec_len(treasure); - ns(Weapon_ref_t) axe; - - // NOTE: if we use end_as_root, we MUST also start as root. - ns(Monster_start_as_root(B)); - ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f)); - ns(Monster_hp_add(B, 300)); - ns(Monster_mana_add(B, 150)); - // We use create_str instead of add because we have no existing string reference. - ns(Monster_name_create_str(B, "Orc")); - // Again we use create because we no existing vector object, only a C-array. - ns(Monster_inventory_create(B, treasure, treasure_count)); - ns(Monster_color_add(B, ns(Color_Red))); - if (1) { - ns(Monster_weapons_start(B)); - ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Sword"), 3)); - // We reuse the axe object later. Note that we dereference a pointer - // because push always returns a short-term pointer to the stored element. - // We could also have created the axe object first and simply pushed it. - axe = *ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Axe"), 5)); - ns(Monster_weapons_end(B)); - } else { - // We can have more control with the table elements added to a vector: - // - ns(Monster_weapons_start(B)); - ns(Monster_weapons_push_start(B)); - ns(Weapon_name_create_str(B, "Sword")); - ns(Weapon_damage_add(B, 3)); - ns(Monster_weapons_push_end(B)); - ns(Monster_weapons_push_start(B)); - ns(Monster_weapons_push_start(B)); - ns(Weapon_name_create_str(B, "Axe")); - ns(Weapon_damage_add(B, 5)); - axe = *ns(Monster_weapons_push_end(B)); - ns(Monster_weapons_end(B)); - } - // Unions can get their type by using a type-specific add/create/start method. - ns(Monster_equipped_Weapon_add(B, axe)); - - ns(Monster_end_as_root(B)); -~~~ -
- - -## Basic Reflection - -The C-API does support reading binary schema (.bfbs) -files via code generated from the `reflection.fbs` schema, and an -[example usage](https://github.com/dvidelabs/flatcc/tree/master/samples/reflection) -shows how to use this. The reflection schema files are pre-generated -in the [runtime distribution](https://github.com/dvidelabs/flatcc/tree/master/include/flatcc/reflection). - - -## Mutations and Reflection - -The C-API does not support mutating reflection like C++ does, nor does -the reader interface support mutating scalars (and it is generally -unsafe to do so even after verification). - -The generated reader interface supports sorting vectors in-place after -casting them to a mutating type because it is not practical to do so -while building a buffer. This is covered in the builder documentation. -The reflection example makes use of this feature to look up objects by -name. - -It is possible to build new buffers using complex objects from existing -buffers as source. This can be very efficient due to direct copy -semantics without endian conversion or temporary stack allocation. - -Scalars, structs and strings can be used as source, as well vectors of -these. - -It is currently not possible to use an existing table or vector of table -as source, but it would be possible to add support for this at some -point. - - -## Namespaces - -The `FLATBUFFERS_WRAP_NAMESPACE` approach used in the tutorial is convenient -when each function has a very long namespace prefix. But it isn't always -the best approach. If the namespace is absent, or simple and -informative, we might as well use the prefix directly. The -[reflection example](https://github.com/dvidelabs/flatcc/blob/master/samples/reflection/bfbs2json.c) -mentioned above uses this approach. - - -## Checking for Present Members - -Not all languages support testing if a field is present, but in C we can -elaborate the reader section of the tutorial with tests for this. Recall -that `mana` was set to the default value `150` and therefore shouldn't -be present. - -
-~~~{.c} - int hp_present = ns(Monster_hp_is_present(monster)); // 1 - int mana_present = ns(Monster_mana_is_present(monster)); // 0 -~~~ -
- -## Alternative ways to add a Union - -In the tutorial we used a single call to add a union. Here we show -different ways to accomplish the same thing. The last form is rarely -used, but is the low-level way to do it. It can be used to group small -values together in the table by adding type and data at different -points in time. - -
-~~~{.c} - ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); - ns(Monster_equipped_add(B, equipped)); - // or alternatively - ns(Monster_equipped_Weapon_add(B, axe); - // or alternatively - ns(Monster_equipped_add_type(B, ns(Equipment_Weapon)); - ns(Monster_equipped_add_member(B, axe)); -~~~ -
- -## Why not integrate with the `flatc` tool? - -[It was considered how the C code generator could be integrated into the -`flatc` tool](https://github.com/dvidelabs/flatcc/issues/1), but it -would either require that the standalone C implementation of the schema -compiler was dropped, or it would lead to excessive code duplication, or -a complicated intermediate representation would have to be invented. -Neither of these alternatives are very attractive, and it isn't a big -deal to use the `flatcc` tool instead of `flatc` given that the -FlatBuffers C runtime library needs to be made available regardless. - - diff --git a/docs-old/source/Compiler.md b/docs-old/source/Compiler.md deleted file mode 100644 index a1a095a4d24..00000000000 --- a/docs-old/source/Compiler.md +++ /dev/null @@ -1,281 +0,0 @@ -Using the schema compiler {#flatbuffers_guide_using_schema_compiler} -========================= - -Usage: - - flatc [ GENERATOR OPTIONS ] [ -o PATH ] [ -I PATH ] FILES... - [ -- FILES...] - -The files are read and parsed in order, and can contain either schemas -or data (see below). Data files are processed according to the definitions of -the most recent schema specified. - -`--` indicates that the following files are binary files in -FlatBuffer format conforming to the schema indicated before it. - -Depending on the flags passed, additional files may -be generated for each file processed: - -For any schema input files, one or more generators can be specified: - -- `--cpp`, `-c` : Generate a C++ header for all definitions in this file (as - `filename_generated.h`). - -- `--java`, `-j` : Generate Java code. - -- `--kotlin` , `--kotlin-kmp` : Generate Kotlin code. - -- `--csharp`, `-n` : Generate C# code. - -- `--go`, `-g` : Generate Go code. - -- `--python`, `-p` : Generate Python code. - -- `--js`, `-s` : Generate JavaScript code. - -- `--ts`, `-T` : Generate TypeScript code. - -- `--php` : Generate PHP code. - -- `--grpc` : Generate RPC stub code for GRPC. - -- `--dart`, `-d` : Generate Dart code. - -- `--lua`, `-l` : Generate Lua code. - -- `--lobster` : Generate Lobster code. - -- `--rust`, `-r` : Generate Rust code. - -- `--swift` : Generate Swift code. - -- `--nim` : Generate Nim code. - - - -For any data input files: - -- `--binary`, `-b` : If data is contained in this file, generate a - `filename.bin` containing the binary flatbuffer (or a different extension - if one is specified in the schema). - -- `--json`, `-t` : If data is contained in this file, generate a - `filename.json` representing the data in the flatbuffer. - -- `--jsonschema` : Generate Json schema - -Additional options: - -- `-o PATH` : Output all generated files to PATH (either absolute, or - relative to the current directory). If omitted, PATH will be the - current directory. PATH should end in your systems path separator, - e.g. `/` or `\`. - -- `-I PATH` : when encountering `include` statements, attempt to load the - files from this path. Paths will be tried in the order given, and if all - fail (or none are specified) it will try to load relative to the path of - the schema file being parsed. - -- `-M` : Print make rules for generated files. - -- `--strict-json` : Require & generate strict JSON (field names are enclosed - in quotes, no trailing commas in tables/vectors). By default, no quotes are - required/generated, and trailing commas are allowed. - -- `--allow-non-utf8` : Pass non-UTF-8 input through parser and emit nonstandard - \x escapes in JSON. (Default is to raise parse error on non-UTF-8 input.) - -- `--natural-utf8` : Output strings with UTF-8 as human-readable strings. - By default, UTF-8 characters are printed as \uXXXX escapes." - -- `--defaults-json` : Output fields whose value is equal to the default value - when writing JSON text. - -- `--no-prefix` : Don't prefix enum values in generated C++ by their enum - type. - -- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in - generated C++. This also implies `--no-prefix`. - -- `--no-emit-min-max-enum-values` : Disable generation of MIN and MAX - enumerated values for scoped enums and prefixed enums. - -- `--gen-includes` : (deprecated), this is the default behavior. - If the original behavior is required (no include - statements) use `--no-includes.` - -- `--no-includes` : Don't generate include statements for included schemas the - generated file depends on (C++ / Python). - -- `--gen-mutable` : Generate additional non-const accessors for mutating - FlatBuffers in-place. - -- `--gen-onefile` : Generate single output file for C#, Go, and Python. - -- `--gen-name-strings` : Generate type name functions for C++. - -- `--gen-object-api` : Generate an additional object-based API. This API is - more convenient for object construction and mutation than the base API, - at the cost of efficiency (object allocation). Recommended only to be used - if other options are insufficient. - -- `--gen-compare` : Generate operator== for object-based API types. - -- `--gen-nullable` : Add Clang \_Nullable for C++ pointer. or @Nullable for Java. - -- `--gen-generated` : Add @Generated annotation for Java. - -- `--gen-jvmstatic` : Add @JvmStatic annotation for Kotlin methods - in companion object for interop from Java to Kotlin. - -- `--gen-all` : Generate not just code for the current schema files, but - for all files it includes as well. If the language uses a single file for - output (by default the case for C++ and JS), all code will end up in - this one file. - -- `--cpp-include` : Adds an #include in generated file - -- `--cpp-ptr-type T` : Set object API pointer type (default std::unique_ptr) - -- `--cpp-str-type T` : Set object API string type (default std::string) - T::c_str(), T::length() and T::empty() must be supported. - The custom type also needs to be constructible from std::string (see the - --cpp-str-flex-ctor option to change this behavior). - -- `--cpp-str-flex-ctor` : Don't construct custom string types by passing - std::string from Flatbuffers, but (char* + length). This allows efficient - construction of custom string types, including zero-copy construction. - -- `--no-cpp-direct-copy` : Don't generate direct copy methods for C++ - object-based API. - -- `--cpp-std CPP_STD` : Generate a C++ code using features of selected C++ standard. - Supported `CPP_STD` values: - * `c++0x` - generate code compatible with old compilers (VS2010), - * `c++11` - use C++11 code generator (default), - * `c++17` - use C++17 features in generated code (experimental). - -- `--object-prefix` : Customise class prefix for C++ object-based API. - -- `--object-suffix` : Customise class suffix for C++ object-based API. - -- `--go-namespace` : Generate the overrided namespace in Golang. - -- `--go-import` : Generate the overrided import for flatbuffers in Golang. - (default is "github.com/google/flatbuffers/go"). - -- `--raw-binary` : Allow binaries without a file_indentifier to be read. - This may crash flatc given a mismatched schema. - -- `--size-prefixed` : Input binaries are size prefixed buffers. - -- `--proto`: Expect input files to be .proto files (protocol buffers). - Output the corresponding .fbs file. - Currently supports: `package`, `message`, `enum`, nested declarations, - `import` (use `-I` for paths), `extend`, `oneof`, `group`. - Does not support, but will skip without error: `option`, `service`, - `extensions`, and most everything else. - -- `--oneof-union` : Translate .proto oneofs to flatbuffer unions. - -- `--grpc` : Generate GRPC interfaces for the specified languages. - -- `--schema`: Serialize schemas instead of JSON (use with -b). This will - output a binary version of the specified schema that itself corresponds - to the reflection/reflection.fbs schema. Loading this binary file is the - basis for reflection functionality. - -- `--bfbs-comments`: Add doc comments to the binary schema files. - -- `--conform FILE` : Specify a schema the following schemas should be - an evolution of. Gives errors if not. Useful to check if schema - modifications don't break schema evolution rules. - -- `--conform-includes PATH` : Include path for the schema given with - `--conform PATH`. - -- `--filename-suffix SUFFIX` : The suffix appended to the generated - file names. Default is '\_generated'. - -- `--filename-ext EXTENSION` : The extension appended to the generated - file names. Default is language-specific (e.g. "h" for C++). This - should not be used when multiple languages are specified. - -- `--include-prefix PATH` : Prefix this path to any generated include - statements. - -- `--keep-prefix` : Keep original prefix of schema include statement. - -- `--reflect-types` : Add minimal type reflection to code generation. - -- `--reflect-names` : Add minimal type/name reflection. - -- `--root-type T` : Select or override the default root_type. - -- `--require-explicit-ids` : When parsing schemas, require explicit ids (id: x). - -- `--force-defaults` : Emit default values in binary output from JSON. - -- `--force-empty` : When serializing from object API representation, force - strings and vectors to empty rather than null. - -- `--force-empty-vectors` : When serializing from object API representation, force - vectors to empty rather than null. - -- `--flexbuffers` : Used with "binary" and "json" options, it generates - data using schema-less FlexBuffers. - -- `--no-warnings` : Inhibit all warning messages. - -- `--cs-global-alias` : Prepend `global::` to all user generated csharp classes and structs. - -- `--json-nested-bytes` : Allow a nested_flatbuffer field to be parsed as a - vector of bytes in JSON, which is unsafe unless checked by a verifier - afterwards. - -- `--python-no-type-prefix-suffix` : Skip emission of Python functions that are prefixed - with typenames - -- `--python-typing` : Generate Python type annotations - -Additional gRPC options: - -- `--grpc-filename-suffix`: `[C++]` An optional suffix for the generated - files' names. For example, compiling gRPC for C++ with - `--grpc-filename-suffix=.fbs` will generate `{name}.fbs.h` and - `{name}.fbs.cc` files. - -- `--grpc-additional-header`: `[C++]` Additional headers to include in the - generated files. - -- `--grpc-search-path`: `[C++]` An optional prefix for the gRPC runtime path. - For example, compiling gRPC for C++ with `--grpc-search-path=some/path` will - generate the following includes: - - ```cpp - #include "some/path/grpcpp/impl/codegen/async_stream.h" - #include "some/path/grpcpp/impl/codegen/async_unary_call.h" - #include "some/path/grpcpp/impl/codegen/method_handler.h" - ... - ``` - -- `--grpc-use-system-headers`: `[C++]` Whether to generate `#include
` - instead of `#include "header.h"` for all headers when compiling gRPC for - C++. For example, compiling gRPC for C++ with `--grpc-use-system-headers` - will generate the following includes: - - ```cpp - #include - #include - #include - ... - ``` - - NOTE: This option can be negated with `--no-grpc-use-system-headers`. - -- `--grpc-python-typed-handlers`: `[Python]` Whether to generate the typed - handlers that use the generated Python classes instead of raw bytes for - requests/responses. - -NOTE: short-form options for generators are deprecated, use the long form -whenever possible. diff --git a/docs-old/source/CppUsage.md b/docs-old/source/CppUsage.md deleted file mode 100644 index 82d6f154aa8..00000000000 --- a/docs-old/source/CppUsage.md +++ /dev/null @@ -1,639 +0,0 @@ -Use in C++ {#flatbuffers_guide_use_cpp} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in C++, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including C++). -This page is designed to cover the nuances of FlatBuffers usage, specific to -C++. - -#### Prerequisites - -This page assumes you have written a FlatBuffers schema and compiled it -with the Schema Compiler. If you have not, please see -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -and [Writing a schema](@ref flatbuffers_guide_writing_schema). - -Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't -matter), you've generated a C++ header called `mygame_generated.h` using the -compiler (e.g. `flatc -c mygame.fbs`), you can now start using this in -your program by including the header. As noted, this header relies on -`flatbuffers/flatbuffers.h`, which should be in your include path. - -## FlatBuffers C++ library code location - -The code for the FlatBuffers C++ library can be found at -`flatbuffers/include/flatbuffers`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/include/flatbuffers). - -## Testing the FlatBuffers C++ library - -The code to test the C++ library can be found at `flatbuffers/tests`. -The test code itself is located in -[test.cpp](https://github.com/google/flatbuffers/blob/master/tests/test.cpp). - -This test file is built alongside `flatc`. To review how to build the project, -please read the [Building](@ref flatbuffers_guide_building) documentation. - -To run the tests, execute `flattests` from the root `flatbuffers/` directory. -For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply -run: `./flattests`. - -## Using the FlatBuffers C++ library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in C++.* - -FlatBuffers supports both reading and writing FlatBuffers in C++. - -To use FlatBuffers in your code, first generate the C++ classes from your -schema with the `--cpp` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write FlatBuffers. - -For example, here is how you would read a FlatBuffer binary file in C++: -First, include the library and generated code. Then read the file into -a `char *` array, which you pass to `GetMonster()`. - -```cpp - #include "flatbuffers/flatbuffers.h" - #include "monster_test_generate.h" - #include // C++ header file for printing - #include // C++ header file for file access - - - std::ifstream infile; - infile.open("monsterdata_test.mon", std::ios::binary | std::ios::in); - infile.seekg(0,std::ios::end); - int length = infile.tellg(); - infile.seekg(0,std::ios::beg); - char *data = new char[length]; - infile.read(data, length); - infile.close(); - - auto monster = GetMonster(data); -``` - -`monster` is of type `Monster *`, and points to somewhere *inside* your -buffer (root object pointers are not the same as `buffer_pointer` \!). -If you look in your generated header, you'll see it has -convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: - -```cpp - std::cout << "hp : " << monster->hp() << std::endl; // '80' - std::cout << "mana : " << monster->mana() << std::endl; // default value of '150' - std::cout << "name : " << monster->name()->c_str() << std::endl; // "MyMonster" -``` - -*Note: That we never stored a `mana` value, so it will return the default.* - -The following attributes are supported: - -- `shared` (on a field): For string fields, this enables the usage of string - pooling (i.e. `CreateSharedString`) as default serialization behavior. - - Specifically, `CreateXxxDirect` functions and `Pack` functions for object - based API (see below) will use `CreateSharedString` to create strings. - -## Object based API {#flatbuffers_cpp_object_based_api} - -FlatBuffers is all about memory efficiency, which is why its base API is written -around using as little as possible of it. This does make the API clumsier -(requiring pre-order construction of all data, and making mutation harder). - -For times when efficiency is less important a more convenient object based API -can be used (through `--gen-object-api`) that is able to unpack & pack a -FlatBuffer into objects and standard STL containers, allowing for convenient -construction, access and mutation. - -To use: - -```cpp - // Autogenerated class from table Monster. - MonsterT monsterobj; - - // Deserialize from buffer into object. - GetMonster(flatbuffer)->UnPackTo(&monsterobj); - - // Update object directly like a C++ class instance. - cout << monsterobj.name; // This is now a std::string! - monsterobj.name = "Bob"; // Change the name. - - // Serialize into new flatbuffer. - FlatBufferBuilder fbb; - fbb.Finish(Monster::Pack(fbb, &monsterobj)); -``` - -The following attributes are specific to the object-based API code generation: - -- `native_inline` (on a field): Because FlatBuffer tables and structs are - optionally present in a given buffer, they are best represented as pointers - (specifically std::unique_ptrs) in the native class since they can be null. - This attribute changes the member declaration to use the type directly - rather than wrapped in a unique_ptr. - -- `native_default("value")` (on a field): For members that are declared - "native_inline", the value specified with this attribute will be included - verbatim in the class constructor initializer list for this member. - -- `native_custom_alloc("custom_allocator")` (on a table or struct): When using the - object-based API all generated NativeTables that are allocated when unpacking - your flatbuffer will use "custom allocator". The allocator is also used by - any std::vector that appears in a table defined with `native_custom_alloc`. - This can be used to provide allocation from a pool for example, for faster - unpacking when using the object-based API. - -Minimal Example: - -schema: - -```cpp - table mytable(native_custom_alloc:"custom_allocator") { - ... - } -``` - -with `custom_allocator` defined before `flatbuffers.h` is included, as: - -```cpp - template struct custom_allocator : public std::allocator { - - typedef T *pointer; - - template - struct rebind { - typedef custom_allocator other; - }; - - pointer allocate(const std::size_t n) { - return std::allocator::allocate(n); - } - - void deallocate(T* ptr, std::size_t n) { - return std::allocator::deallocate(ptr,n); - } - - custom_allocator() throw() {} - - template - custom_allocator(const custom_allocator&) throw() {} - }; -``` - -- `native_type("type")` (on a struct): In some cases, a more optimal C++ data -type exists for a given struct. For example, the following schema: - -```cpp - struct Vec2 { - x: float; - y: float; - } -``` - -generates the following Object-Based API class: - -```cpp - struct Vec2T : flatbuffers::NativeTable { - float x; - float y; - }; -``` - -However, it can be useful to instead use a user-defined C++ type since it -can provide more functionality, eg. - -```cpp - struct vector2 { - float x = 0, y = 0; - vector2 operator+(vector2 rhs) const { ... } - vector2 operator-(vector2 rhs) const { ... } - float length() const { ... } - // etc. - }; -``` - -The `native_type` attribute will replace the usage of the generated class -with the given type. So, continuing with the example, the generated -code would use `vector2` in place of `Vec2T` for all generated code of -the Object-Based API. - -However, because the `native_type` is unknown to flatbuffers, the user must -provide the following functions to aide in the serialization process: - -```cpp - namespace flatbuffers { - Vec2 Pack(const vector2& obj); - vector2 UnPack(const Vec2& obj); - } -``` - -- `native_type_pack_name("name")` (on a struct when `native_type` is - specified, too): when you want to use the same `native_type` multiple times - (e. g. with different precision) you must make the names of the Pack/UnPack - functions unique, otherwise you will run into compile errors. This attribute - appends a name to the expected Pack/UnPack functions. So when you - specify `native_type_pack_name("Vec2")` in the above example you now need to - implement these serialization functions instead: - -```cpp - namespace flatbuffers { - Vec2 PackVec2(const vector2& obj); - vector2 UnPackVec2(const Vec2& obj); - } -``` - -Finally, the following top-level attributes: - -- `native_include("path")` (at file level): Because the `native_type` attribute - can be used to introduce types that are unknown to flatbuffers, it may be - necessary to include "external" header files in the generated code. This - attribute can be used to directly add an #include directive to the top of - the generated code that includes the specified path directly. - -- `force_align`: this attribute may not be respected in the object API, - depending on the aligned of the allocator used with `new`. - -# External references - -An additional feature of the object API is the ability to allow you to load -multiple independent FlatBuffers, and have them refer to eachothers objects -using hashes which are then represented as typed pointers in the object API. - -To make this work have a field in the objects you want to referred to which is -using the string hashing feature (see `hash` attribute in the -[schema](@ref flatbuffers_guide_writing_schema) documentation). Then you have -a similar hash in the field referring to it, along with a `cpp_type` -attribute specifying the C++ type this will refer to (this can be any C++ -type, and will get a `*` added). - -Then, in JSON or however you create these buffers, make sure they use the -same string (or hash). - -When you call `UnPack` (or `Create`), you'll need a function that maps from -hash to the object (see `resolver_function_t` for details). - -# Using different pointer types - -By default the object tree is built out of `std::unique_ptr`, but you can -influence this either globally (using the `--cpp-ptr-type` argument to -`flatc`) or per field (using the `cpp_ptr_type` attribute) to by any smart -pointer type (`my_ptr`), or by specifying `naked` as the type to get `T *` -pointers. Unlike the smart pointers, naked pointers do not manage memory for -you, so you'll have to manage their lifecycles manually. To reference the -pointer type specified by the `--cpp-ptr-type` argument to `flatc` from a -flatbuffer field set the `cpp_ptr_type` attribute to `default_ptr_type`. - -# Using different string type - -By default the object tree is built out of `std::string`, but you can -influence this either globally (using the `--cpp-str-type` argument to -`flatc`) or per field using the `cpp_str_type` attribute. - -The type must support `T::c_str()`, `T::length()` and `T::empty()` as member functions. - -Further, the type must be constructible from std::string, as by default a -std::string instance is constructed and then used to initialize the custom -string type. This behavior impedes efficient and zero-copy construction of -custom string types; the `--cpp-str-flex-ctor` argument to `flatc` or the -per field attribute `cpp_str_flex_ctor` can be used to change this behavior, -so that the custom string type is constructed by passing the pointer and -length of the FlatBuffers String. The custom string class will require a -constructor in the following format: `custom_str_class(const char *, size_t)`. -Please note that the character array is not guaranteed to be NULL terminated, -you should always use the provided size to determine end of string. - -## Reflection (& Resizing) - -There is experimental support for reflection in FlatBuffers, allowing you to -read and write data even if you don't know the exact format of a buffer, and -even allows you to change sizes of strings and vectors in-place. - -The way this works is very elegant; there is actually a FlatBuffer schema that -describes schemas (\!) which you can find in `reflection/reflection.fbs`. -The compiler, `flatc`, can write out any schemas it has just parsed as a binary -FlatBuffer, corresponding to this meta-schema. - -Loading in one of these binary schemas at runtime allows you traverse any -FlatBuffer data that corresponds to it without knowing the exact format. You -can query what fields are present, and then read/write them after. - -For convenient field manipulation, you can include the header -`flatbuffers/reflection.h` which includes both the generated code from the meta -schema, as well as a lot of helper functions. - -And example of usage, for the time being, can be found in -`test.cpp/ReflectionTest()`. - -## Mini Reflection - -A more limited form of reflection is available for direct inclusion in -generated code, which doesn't do any (binary) schema access at all. It was designed -to keep the overhead of reflection as low as possible (on the order of 2-6 -bytes per field added to your executable), but doesn't contain all the -information the (binary) schema contains. - -You add this information to your generated code by specifying `--reflect-types` -(or instead `--reflect-names` if you also want field / enum names). - -You can now use this information, for example to print a FlatBuffer to text: - - auto s = flatbuffers::FlatBufferToString(flatbuf, MonsterTypeTable()); - -`MonsterTypeTable()` is declared in the generated code for each type. The -string produced is very similar to the JSON produced by the `Parser` based -text generator. - -You'll need `flatbuffers/minireflect.h` for this functionality. In there is also -a convenient visitor/iterator so you can write your own output / functionality -based on the mini reflection tables without having to know the FlatBuffers or -reflection encoding. - -## Storing maps / dictionaries in a FlatBuffer - -FlatBuffers doesn't support maps natively, but there is support to -emulate their behavior with vectors and binary search, which means you -can have fast lookups directly from a FlatBuffer without having to unpack -your data into a `std::map` or similar. - -To use it: -- Designate one of the fields in a table as they "key" field. You do this - by setting the `key` attribute on this field, e.g. - `name:string (key)`. - You may only have one key field, and it must be of string or scalar type. -- Write out tables of this type as usual, collect their offsets in an - array or vector. -- Instead of `CreateVector`, call `CreateVectorOfSortedTables`, - which will first sort all offsets such that the tables they refer to - are sorted by the key field, then serialize it. -- Now when you're accessing the FlatBuffer, you can use `Vector::LookupByKey` - instead of just `Vector::Get` to access elements of the vector, e.g.: - `myvector->LookupByKey("Fred")`, which returns a pointer to the - corresponding table type, or `nullptr` if not found. - `LookupByKey` performs a binary search, so should have a similar speed to - `std::map`, though may be faster because of better caching. `LookupByKey` - only works if the vector has been sorted, it will likely not find elements - if it hasn't been sorted. - -## Direct memory access - -As you can see from the above examples, all elements in a buffer are -accessed through generated accessors. This is because everything is -stored in little endian format on all platforms (the accessor -performs a swap operation on big endian machines), and also because -the layout of things is generally not known to the user. - -For structs, layout is deterministic and guaranteed to be the same -across platforms (scalars are aligned to their -own size, and structs themselves to their largest member), and you -are allowed to access this memory directly by using `sizeof()` and -`memcpy` on the pointer to a struct, or even an array of structs. - -To compute offsets to sub-elements of a struct, make sure they -are a structs themselves, as then you can use the pointers to -figure out the offset without having to hardcode it. This is -handy for use of arrays of structs with calls like `glVertexAttribPointer` -in OpenGL or similar APIs. - -It is important to note is that structs are still little endian on all -machines, so only use tricks like this if you can guarantee you're not -shipping on a big endian machine (an `assert(FLATBUFFERS_LITTLEENDIAN)` -would be wise). - -## Access of untrusted buffers - -The generated accessor functions access fields over offsets, which is -very quick. These offsets are not verified at run-time, so a malformed -buffer could cause a program to crash by accessing random memory. - -When you're processing large amounts of data from a source you know (e.g. -your own generated data on disk), this is acceptable, but when reading -data from the network that can potentially have been modified by an -attacker, this is undesirable. - -For this reason, you can optionally use a buffer verifier before you -access the data. This verifier will check all offsets, all sizes of -fields, and null termination of strings to ensure that when a buffer -is accessed, all reads will end up inside the buffer. - -Each root type will have a verification function generated for it, -e.g. for `Monster`, you can call: - -```cpp - bool ok = VerifyMonsterBuffer(Verifier(buf, len)); -``` - -if `ok` is true, the buffer is safe to read. - -Besides untrusted data, this function may be useful to call in debug -mode, as extra insurance against data being corrupted somewhere along -the way. - -While verifying a buffer isn't "free", it is typically faster than -a full traversal (since any scalar data is not actually touched), -and since it may cause the buffer to be brought into cache before -reading, the actual overhead may be even lower than expected. - -In specialized cases where a denial of service attack is possible, -the verifier has two additional constructor arguments that allow -you to limit the nesting depth and total amount of tables the -verifier may encounter before declaring the buffer malformed. The default is -`Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)` which -should be sufficient for most uses. - -## Text & schema parsing - -Using binary buffers with the generated header provides a super low -overhead use of FlatBuffer data. There are, however, times when you want -to use text formats, for example because it interacts better with source -control, or you want to give your users easy access to data. - -Another reason might be that you already have a lot of data in JSON -format, or a tool that generates JSON, and if you can write a schema for -it, this will provide you an easy way to use that data directly. - -(see the schema documentation for some specifics on the JSON format -accepted). - -Schema evolution compatibility for the JSON format follows the same rules as the binary format (JSON formatted data will be forwards/backwards compatible with schemas that evolve in a compatible way). - -There are two ways to use text formats: - -#### Using the compiler as a conversion tool - -This is the preferred path, as it doesn't require you to add any new -code to your program, and is maximally efficient since you can ship with -binary data. The disadvantage is that it is an extra step for your -users/developers to perform, though you might be able to automate it. - - flatc -b myschema.fbs mydata.json - -This will generate the binary file `mydata_wire.bin` which can be loaded -as before. - -#### Making your program capable of loading text directly - -This gives you maximum flexibility. You could even opt to support both, -i.e. check for both files, and regenerate the binary from text when -required, otherwise just load the binary. - -This option is currently only available for C++, or Java through JNI. - -As mentioned in the section "Building" above, this technique requires -you to link a few more files into your program, and you'll want to include -`flatbuffers/idl.h`. - -Load text (either a schema or json) into an in-memory buffer (there is a -convenient `LoadFile()` utility function in `flatbuffers/util.h` if you -wish). Construct a parser: - -```cpp - flatbuffers::Parser parser; -``` - -Now you can parse any number of text files in sequence: - -```cpp - parser.Parse(text_file.c_str()); -``` - -This works similarly to how the command-line compiler works: a sequence -of files parsed by the same `Parser` object allow later files to -reference definitions in earlier files. Typically this means you first -load a schema file (which populates `Parser` with definitions), followed -by one or more JSON files. - -As optional argument to `Parse`, you may specify a null-terminated list of -include paths. If not specified, any include statements try to resolve from -the current directory. - -If there were any parsing errors, `Parse` will return `false`, and -`Parser::error_` contains a human readable error string with a line number -etc, which you should present to the creator of that file. - -After each JSON file, the `Parser::fbb` member variable is the -`FlatBufferBuilder` that contains the binary buffer version of that -file, that you can access as described above. - -`samples/sample_text.cpp` is a code sample showing the above operations. - -## Threading - -Reading a FlatBuffer does not touch any memory outside the original buffer, -and is entirely read-only (all const), so is safe to access from multiple -threads even without synchronisation primitives. - -Creating a FlatBuffer is not thread safe. All state related to building -a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory -outside of it is touched. To make this thread safe, either do not -share instances of FlatBufferBuilder between threads (recommended), or -manually wrap it in synchronisation primitives. There's no automatic way to -accomplish this, by design, as we feel multithreaded construction -of a single buffer will be rare, and synchronisation overhead would be costly. - -## Advanced union features - -The C++ implementation currently supports vectors of unions (i.e. you can -declare a field as `[T]` where `T` is a union type instead of a table type). It -also supports structs and strings in unions, besides tables. - -For an example of these features, see `tests/union_vector`, and -`UnionVectorTest` in `test.cpp`. - -Since these features haven't been ported to other languages yet, if you -choose to use them, you won't be able to use these buffers in other languages -(`flatc` will refuse to compile a schema that uses these features). - -These features reduce the amount of "table wrapping" that was previously -needed to use unions. - -To use scalars, simply wrap them in a struct. - -## Depth limit of nested objects and stack-overflow control -The parser of Flatbuffers schema or json-files is kind of recursive parser. -To avoid stack-overflow problem the parser has a built-in limiter of -recursion depth. Number of nested declarations in a schema or number of -nested json-objects is limited. By default, this depth limit set to `64`. -It is possible to override this limit with `FLATBUFFERS_MAX_PARSING_DEPTH` -definition. This definition can be helpful for testing purposes or embedded -applications. For details see [build](@ref flatbuffers_guide_building) of -CMake-based projects. - -## Dependence from C-locale {#flatbuffers_locale_cpp} -The Flatbuffers [grammar](@ref flatbuffers grammar) uses ASCII -character set for identifiers, alphanumeric literals, reserved words. - -Internal implementation of the Flatbuffers depends from functions which -depend from C-locale: `strtod()` or `strtof()`, for example. -The library expects the dot `.` symbol as the separator of an integer -part from the fractional part of a float number. -Another separator symbols (`,` for example) will break the compatibility -and may lead to an error while parsing a Flatbuffers schema or a json file. - -The Standard C locale is a global resource, there is only one locale for -the entire application. Some modern compilers and platforms have -locale-independent or locale-narrow functions `strtof_l`, `strtod_l`, -`strtoll_l`, `strtoull_l` to resolve this dependency. -These functions use specified locale rather than the global or per-thread -locale instead. They are part of POSIX-2008 but not part of the C/C++ -standard library, therefore, may be missing on some platforms. -The Flatbuffers library try to detect these functions at configuration and -compile time: -- CMake `"CMakeLists.txt"`: - - Check existence of `strtol_l` and `strtod_l` in the ``. -- Compile-time `"/include/base.h"`: - - `_MSC_VER >= 1900`: MSVC2012 or higher if build with MSVC. - - `_XOPEN_SOURCE>=700`: POSIX-2008 if build with GCC/Clang. - -After detection, the definition `FLATBUFFERS_LOCALE_INDEPENDENT` will be -set to `0` or `1`. -To override or stop this detection use CMake `-DFLATBUFFERS_LOCALE_INDEPENDENT={0|1}` -or predefine `FLATBUFFERS_LOCALE_INDEPENDENT` symbol. - -To test the compatibility of the Flatbuffers library with -a specific locale use the environment variable `FLATBUFFERS_TEST_LOCALE`: -```sh ->FLATBUFFERS_TEST_LOCALE="" ./flattests ->FLATBUFFERS_TEST_LOCALE="ru_RU.CP1251" ./flattests -``` - -## Support of floating-point numbers -The Flatbuffers library assumes that a C++ compiler and a CPU are -compatible with the `IEEE-754` floating-point standard. -The schema and json parser may fail if `fast-math` or `/fp:fast` mode is active. - -### Support of hexadecimal and special floating-point numbers -According to the [grammar](@ref flatbuffers_grammar) `fbs` and `json` files -may use hexadecimal and special (`NaN`, `Inf`) floating-point literals. -The Flatbuffers uses `strtof` and `strtod` functions to parse floating-point -literals. The Flatbuffers library has a code to detect a compiler compatibility -with the literals. If necessary conditions are met the preprocessor constant -`FLATBUFFERS_HAS_NEW_STRTOD` will be set to `1`. -The support of floating-point literals will be limited at compile time -if `FLATBUFFERS_HAS_NEW_STRTOD` constant is less than `1`. -In this case, schemas with hexadecimal or special literals cannot be used. - -### Comparison of floating-point NaN values -The floating-point `NaN` (`not a number`) is special value which -representing an undefined or unrepresentable value. -`NaN` may be explicitly assigned to variables, typically as a representation -for missing values or may be a result of a mathematical operation. -The `IEEE-754` defines two kind of `NaNs`: -- Quiet NaNs, or `qNaNs`. -- Signaling NaNs, or `sNaNs`. - -According to the `IEEE-754`, a comparison with `NaN` always returns -an unordered result even when compared with itself. As a result, a whole -Flatbuffers object will be not equal to itself if has one or more `NaN`. -Flatbuffers scalar fields that have the default value are not actually stored -in the serialized data but are generated in code (see [Writing a schema](@ref flatbuffers_guide_writing_schema)). -Scalar fields with `NaN` defaults break this behavior. -If a schema has a lot of `NaN` defaults the Flatbuffers can override -the unordered comparison by the ordered: `(NaN==NaN)->true`. -This ordered comparison is enabled when compiling a program with the symbol -`FLATBUFFERS_NAN_DEFAULTS` defined. -Additional computations added by `FLATBUFFERS_NAN_DEFAULTS` are very cheap -if GCC or Clang used. These compilers have a compile-time implementation -of `isnan` checking which MSVC does not. - -
diff --git a/docs-old/source/CsharpUsage.md b/docs-old/source/CsharpUsage.md deleted file mode 100644 index 84fa697a281..00000000000 --- a/docs-old/source/CsharpUsage.md +++ /dev/null @@ -1,265 +0,0 @@ -Use in C# {#flatbuffers_guide_use_c-sharp} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in C#, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages (including C#). -This page is designed to cover the nuances of FlatBuffers usage, -specific to C#. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers C# code location - -The code for the FlatBuffers C# library can be found at -`flatbuffers/net/FlatBuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/net/ -FlatBuffers). - -## Building the FlatBuffers C# library - -The `FlatBuffers.csproj` project contains multitargeting for .NET Standard 2.1, -.NET 6 and .NET 8. - -You can build for a specific framework target when using the cross-platform -[.NET Core SDK](https://dotnet.microsoft.com/download) by adding the `-f` -command line option: - -~~~{.sh} - dotnet build -f netstandard2.1 "FlatBuffers.csproj" -~~~ - -The `FlatBuffers.csproj` project also provides support for defining various -conditional compilation symbols (see "Conditional compilation symbols" section -below) using the `-p` command line option: - -~~~{.sh} - dotnet build -f netstandard2.1 -p:ENABLE_SPAN_T=true -p:UNSAFE_BYTEBUFFER=true "FlatBuffers.csproj" -~~~ - -## Testing the FlatBuffers C# library - -The code to test the libraries can be found at `flatbuffers/tests`. - -The test code for C# is located in the [FlatBuffers.Test](https://github.com/ -google/flatbuffers/tree/master/tests/FlatBuffers.Test) subfolder. To run the -tests, open `FlatBuffers.Test.csproj` in [Visual Studio]( -https://www.visualstudio.com), and compile/run the project. - -Optionally, you can run this using [Mono](http://www.mono-project.com/) instead. -Once you have installed Mono, you can run the tests from the command line -by running the following commands from inside the `FlatBuffers.Test` folder: - -~~~{.sh} - mcs *.cs ../MyGame/Example/*.cs ../../net/FlatBuffers/*.cs - mono Assert.exe -~~~ - -## Using the FlatBuffers C# library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in C#.* - -FlatBuffers supports reading and writing binary FlatBuffers in C#. - -To use FlatBuffers in your own code, first generate C# classes from your -schema with the `--csharp` option to `flatc`. -Then you can include both FlatBuffers and the generated code to read -or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in C#: -First, import the library and generated code. Then, you read a FlatBuffer binary -file into a `byte[]`. You then turn the `byte[]` into a `ByteBuffer`, which you -pass to the `GetRootAsMyRootType` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - using MyGame.Example; - using Google.FlatBuffers; - - // This snippet ignores exceptions for brevity. - byte[] data = File.ReadAllBytes("monsterdata_test.mon"); - - ByteBuffer bb = new ByteBuffer(data); - Monster monster = Monster.GetRootAsMonster(bb); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access the data from the `Monster monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - short hp = monster.Hp; - Vec3 pos = monster.Pos; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -C# code naming follows standard C# style with PascalCasing identifiers, -e.g. `GetRootAsMyRootType`. Also, values (except vectors and unions) are -available as properties instead of parameterless accessor methods. -The performance-enhancing methods to which you can pass an already created -object are prefixed with `Get`, e.g.: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - // property - var pos = monster.Pos; - - // method filling a preconstructed object - var preconstructedPos = new Vec3(); - monster.GetPos(preconstructedPos); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Storing dictionaries in a FlatBuffer - -FlatBuffers doesn't support dictionaries natively, but there is support to -emulate their behavior with vectors and binary search, which means you -can have fast lookups directly from a FlatBuffer without having to unpack -your data into a `Dictionary` or similar. - -To use it: -- Designate one of the fields in a table as the "key" field. You do this - by setting the `key` attribute on this field, e.g. - `name:string (key)`. - You may only have one key field, and it must be of string or scalar type. -- Write out tables of this type as usual, collect their offsets in an - array. -- Instead of calling standard generated method, - e.g.: `Monster.createTestarrayoftablesVector`, - call `CreateSortedVectorOfMonster` in C# - which will first sort all offsets such that the tables they refer to - are sorted by the key field, then serialize it. -- Now when you're accessing the FlatBuffer, you can use - the `ByKey` accessor to access elements of the vector, e.g.: - `monster.TestarrayoftablesByKey("Frodo")` in C#, - which returns an object of the corresponding table type, - or `null` if not found. - `ByKey` performs a binary search, so should have a similar - speed to `Dictionary`, though may be faster because of better caching. - `ByKey` only works if the vector has been sorted, it will - likely not find elements if it hasn't been sorted. - -## Buffer verification - -As mentioned in [C++ Usage](@ref flatbuffers_guide_use_cpp) buffer -accessor functions do not verify buffer offsets at run-time. -If it is necessary, you can optionally use a buffer verifier before you -access the data. This verifier will check all offsets, all sizes of -fields, and null termination of strings to ensure that when a buffer -is accessed, all reads will end up inside the buffer. - -Each root type will have a verification function generated for it, -e.g. `Monster.VerifyMonster`. This can be called as shown: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - var ok = Monster.VerifyMonster(buf); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -if `ok` is true, the buffer is safe to read. - -For a more detailed control of verification `MonsterVerify.Verify` -for `Monster` type can be used: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - # Sequence of calls - FlatBuffers.Verifier verifier = new FlatBuffers.Verifier(buf); - var ok = verifier.VerifyBuffer("MONS", false, MonsterVerify.Verify); - - # Or single line call - var ok = new FlatBuffers.Verifier(bb).setStringCheck(true).\ - VerifyBuffer("MONS", false, MonsterVerify.Verify); - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -if `ok` is true, the buffer is safe to read. - -A second parameter of `verifyBuffer` specifies whether buffer content is -size prefixed or not. In the example above, the buffer is assumed to not include -size prefix (`false`). - -Verifier supports options that can be set using appropriate fluent methods: -* SetMaxDepth - limit the nesting depth. Default: 1000000 -* SetMaxTables - total amount of tables the verifier may encounter. Default: 64 -* SetAlignmentCheck - check content alignment. Default: True -* SetStringCheck - check if strings contain termination '0' character. Default: true - - -## Text parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from C#, though you could use the C++ parser through native call -interfaces available to each language. Please see the -C++ documentation for more on text parsing. - -## Object based API - -FlatBuffers is all about memory efficiency, which is why its base API is written -around using as little as possible of it. This does make the API clumsier -(requiring pre-order construction of all data, and making mutation harder). - -For times when efficiency is less important a more convenient object based API -can be used (through `--gen-object-api`) that is able to unpack & pack a -FlatBuffer into objects and standard `System.Collections.Generic` containers, -allowing for convenient construction, access and mutation. - -To use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - // Deserialize from buffer into object. - MonsterT monsterobj = GetMonster(flatbuffer).UnPack(); - - // Update object directly like a C# class instance. - Console.WriteLine(monsterobj.Name); - monsterobj.Name = "Bob"; // Change the name. - - // Serialize into new flatbuffer. - FlatBufferBuilder fbb = new FlatBufferBuilder(1); - fbb.Finish(Monster.Pack(fbb, monsterobj).Value); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -### Json Serialization - -An additional feature of the object API is the ability to allow you to -serialize & deserialize a JSON text. -To use Json Serialization, add `--cs-gen-json-serializer` option to `flatc` and -add `Newtonsoft.Json` nuget package to csproj. This requires explicitly setting -the `--gen-object-api` option as well. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} - // Deserialize MonsterT from json - string jsonText = File.ReadAllText(@"Resources/monsterdata_test.json"); - MonsterT mon = MonsterT.DeserializeFromJson(jsonText); - - // Serialize MonsterT to json - string jsonText2 = mon.SerializeToJson(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -* Limitation - * `hash` attribute currently not supported. -* NuGet package Dependency - * [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) - -## Conditional compilation symbols - -There are three conditional compilation symbols that have an impact on -performance/features of the C# `ByteBuffer` implementation. - -* `UNSAFE_BYTEBUFFER` - - This will use unsafe code to manipulate the underlying byte array. This can - yield a reasonable performance increase. - -* `BYTEBUFFER_NO_BOUNDS_CHECK` - - This will disable the bounds check asserts to the byte array. This can yield a - small performance gain in normal code. - -* `ENABLE_SPAN_T` - - This will enable reading and writing blocks of memory with a `Span` instead - of just `T[]`. You can also enable writing directly to shared memory or other - types of memory by providing a custom implementation of `ByteBufferAllocator`. - `ENABLE_SPAN_T` also requires `UNSAFE_BYTEBUFFER` to be defined, or .NET - Standard 2.1. - -Using `UNSAFE_BYTEBUFFER` and `BYTEBUFFER_NO_BOUNDS_CHECK` together can yield a -performance gain of ~15% for some operations, however doing so is potentially -dangerous. Do so at your own risk! - -
diff --git a/docs-old/source/DartUsage.md b/docs-old/source/DartUsage.md deleted file mode 100644 index 515a64411c6..00000000000 --- a/docs-old/source/DartUsage.md +++ /dev/null @@ -1,131 +0,0 @@ -Use in Dart {#flatbuffers_guide_use_dart} -=========== - -## Before you get started - -Before diving into the FlatBuffers usage in Dart, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Dart). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Dart. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Dart library code location - -The code for the FlatBuffers Dart library can be found at -`flatbuffers/dart`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/dart). - -## Testing the FlatBuffers Dart library - -The code to test the Dart library can be found at `flatbuffers/tests`. -The test code itself is located in [dart_test.dart](https://github.com/google/ -flatbuffers/blob/master/tests/dart_test.dart). - -To run the tests, use the [DartTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/DartTest.sh) shell script. - -*Note: The shell script requires the [Dart SDK](https://www.dartlang.org/tools/sdk) -to be installed.* - -## Using the FlatBuffers Dart library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Dart.* - -FlatBuffers supports reading and writing binary FlatBuffers in Dart. - -To use FlatBuffers in your own code, first generate Dart classes from your -schema with the `--dart` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Dart: First, -include the library and generated code. Then read a FlatBuffer binary file into -a `List`, which you pass to the factory constructor for `Monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} -import 'dart:io' as io; - -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; - -List data = await new io.File('monster.dat').readAsBytes(); -var monster = new myGame.Monster(data); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} -var hp = monster.hp; -var pos = monster.pos; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Differences from the Dart SDK Front End flat_buffers - -The work in this repository is signfiicantly based on the implementation used -internally by the Dart SDK in the front end/analyzer package. Several -significant changes have been made. - -1. Support for packed boolean lists has been removed. This is not standard - in other implementations and is not compatible with them. Do note that, - like in the JavaScript implementation, __null values in boolean lists - will be treated as false__. It is also still entirely possible to pack data - in a single scalar field, but that would have to be done on the application - side. -2. The SDK implementation supports enums with regular Dart enums, which - works if enums are always indexed at 1; however, FlatBuffers does not - require that. This implementation uses specialized enum-like classes to - ensure proper mapping from FlatBuffers to Dart and other platforms. -3. The SDK implementation does not appear to support FlatBuffer structs or - vectors of structs - it treated everything as a built-in scalar or a table. - This implementation treats structs in a way that is compatible with other - non-Dart implementations, and properly handles vectors of structs. Many of - the methods prefixed with 'low' have been prepurposed to support this. -4. The SDK implementation treats int64 and uint64 as float64s. This - implementation does not. This may cause problems with JavaScript - compatibility - however, it should be possible to use the JavaScript - implementation, or to do a customized implementation that treats all 64 bit - numbers as floats. Supporting the Dart VM and Flutter was a more important - goal of this implementation. Support for 16 bit integers was also added. -5. The code generation in this offers an "ObjectBuilder", which generates code - very similar to the SDK classes that consume FlatBuffers, as well as Builder - classes, which produces code which more closely resembles the builders in - other languages. The ObjectBuilder classes are easier to use, at the cost of - additional references allocated. - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Dart, though you could use the C++ parser through Dart Native Extensions. -Please see the C++ documentation for more on text parsing (note that this is -not currently an option in Flutter - follow [this issue](https://github.com/flutter/flutter/issues/7053) -for the latest). - -## Object based API - -FlatBuffers is all about memory efficiency, which is why its base API is written -around using as little as possible of it. This does make the API clumsier -(requiring pre-order construction of all data, and making mutation harder). - -For times when efficiency is less important a more convenient object based API -can be used (through `--gen-object-api`) that is able to unpack & pack a FlatBuffer -into objects and lists, allowing for convenient construction, access and mutation. - -To use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} - // Deserialize from buffer into object. - MonsterT monster = Monster(flatbuffer).unpack(); - - // Update object directly like a Dart class instance. - print(monster.Name); - monster.Name = "Bob"; // Change the name. - - // Serialize into new flatbuffer. - final fbb = Builder(); - fbb.Finish(monster.pack(fbb)); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs-old/source/FlatBuffers.md b/docs-old/source/FlatBuffers.md deleted file mode 100644 index e0c24cef432..00000000000 --- a/docs-old/source/FlatBuffers.md +++ /dev/null @@ -1,188 +0,0 @@ -FlatBuffers {#flatbuffers_index} -=========== - -# Overview {#flatbuffers_overview} - -[FlatBuffers](@ref flatbuffers_overview) is an efficient cross platform -serialization library for C++, C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift. -It was originally created at Google for game development and other -performance-critical applications. - -It is available as Open Source on [GitHub](http://github.com/google/flatbuffers) -under the Apache license, v2 (see LICENSE). - -## Why use FlatBuffers? - -- **Access to serialized data without parsing/unpacking** - What sets - FlatBuffers apart is that it represents hierarchical data in a flat - binary buffer in such a way that it can still be accessed directly - without parsing/unpacking, while also still supporting data - structure evolution (forwards/backwards compatibility). - -- **Memory efficiency and speed** - The only memory needed to access - your data is that of the buffer. It requires 0 additional allocations - (in C++, other languages may vary). FlatBuffers is also very - suitable for use with mmap (or streaming), requiring only part of the - buffer to be in memory. Access is close to the speed of raw - struct access with only one extra indirection (a kind of vtable) to - allow for format evolution and optional fields. It is aimed at - projects where spending time and space (many memory allocations) to - be able to access or construct serialized data is undesirable, such - as in games or any other performance sensitive applications. See the - [benchmarks](@ref flatbuffers_benchmarks) for details. - -- **Flexible** - Optional fields means not only do you get great - forwards and backwards compatibility (increasingly important for - long-lived games: don't have to update all data with each new - version!). It also means you have a lot of choice in what data you - write and what data you don't, and how you design data structures. - -- **Tiny code footprint** - Small amounts of generated code, and just - a single small header as the minimum dependency, which is very easy - to integrate. Again, see the benchmark section for details. - -- **Strongly typed** - Errors happen at compile time rather than - manually having to write repetitive and error prone run-time checks. - Useful code can be generated for you. - -- **Convenient to use** - Generated C++ code allows for terse access - & construction code. Then there's optional functionality for parsing - schemas and JSON-like text representations at runtime efficiently if - needed (faster and more memory efficient than other JSON - parsers). - - Java, Kotlin and Go code supports object-reuse. C# has efficient struct based - accessors. - -- **Cross platform code with no dependencies** - C++ code will work - with any recent gcc/clang and VS2010. Comes with build files for the tests & - samples (Android .mk files, and cmake for all other platforms). - -### Why not use Protocol Buffers, or .. ? - -Protocol Buffers is indeed relatively similar to FlatBuffers, -with the primary difference being that FlatBuffers does not need a parsing/ -unpacking step to a secondary representation before you can -access data, often coupled with per-object memory allocation. The code -is an order of magnitude bigger, too. Protocol Buffers has no optional -text import/export. - -### But all the cool kids use JSON! - -JSON is very readable (which is why we use it as our optional text -format) and very convenient when used together with dynamically typed -languages (such as JavaScript). When serializing data from statically -typed languages, however, JSON not only has the obvious drawback of runtime -inefficiency, but also forces you to write *more* code to access data -(counterintuitively) due to its dynamic-typing serialization system. -In this context, it is only a better choice for systems that have very -little to no information ahead of time about what data needs to be stored. - -If you do need to store data that doesn't fit a schema, FlatBuffers also -offers a schema-less (self-describing) version! - -Read more about the "why" of FlatBuffers in the -[white paper](@ref flatbuffers_white_paper). - -### Who uses FlatBuffers? -- [Cocos2d-x](http://www.cocos2d-x.org/), the #1 open source mobile game - engine, uses it to serialize all their - [game data](http://www.cocos2d-x.org/reference/native-cpp/V3.5/d7/d2d/namespaceflatbuffers.html). -- [Facebook](http://facebook.com/) uses it for client-server communication in - their Android app. They have a nice - [article](https://code.facebook.com/posts/872547912839369/improving-facebook-s-performance-on-android-with-flatbuffers/) - explaining how it speeds up loading their posts. -- [Fun Propulsion Labs](https://developers.google.com/games/#Tools) - at Google uses it extensively in all their libraries and games. - -## Usage in brief - -This section is a quick rundown of how to use this system. Subsequent -sections provide a more in-depth usage guide. - -- Write a schema file that allows you to define the data structures - you may want to serialize. Fields can have a scalar type - (ints/floats of all sizes), or they can be a: string; array of any type; - reference to yet another object; or, a set of possible objects (unions). - Fields are optional and have defaults, so they don't need to be - present for every object instance. - -- Use `flatc` (the FlatBuffer compiler) to generate a C++ header (or - Java/Kotlin/C#/Go/Python.. classes) with helper classes to access and construct - serialized data. This header (say `mydata_generated.h`) only depends on - `flatbuffers.h`, which defines the core functionality. - -- Use the `FlatBufferBuilder` class to construct a flat binary buffer. - The generated functions allow you to add objects to this - buffer recursively, often as simply as making a single function call. - -- Store or send your buffer somewhere! - -- When reading it back, you can obtain the pointer to the root object - from the binary buffer, and from there traverse it conveniently - in-place with `object->field()`. - -## In-depth documentation - -- How to [build the compiler](@ref flatbuffers_guide_building) and samples on - various platforms. -- How to [use the compiler](@ref flatbuffers_guide_using_schema_compiler). -- How to [write a schema](@ref flatbuffers_guide_writing_schema). -- How to [use the generated C++ code](@ref flatbuffers_guide_use_cpp) in your - own programs. -- How to [use the generated Java code](@ref flatbuffers_guide_use_java) - in your own programs. -- How to [use the generated C# code](@ref flatbuffers_guide_use_c-sharp) - in your own programs. -- How to [use the generated Kotlin code](@ref flatbuffers_guide_use_kotlin) - in your own programs. -- How to [use the generated Go code](@ref flatbuffers_guide_use_go) in your - own programs. -- How to [use the generated Lua code](@ref flatbuffers_guide_use_lua) in your - own programs. -- How to [use the generated JavaScript code](@ref flatbuffers_guide_use_javascript) in your - own programs. -- How to [use the generated TypeScript code](@ref flatbuffers_guide_use_typescript) in your - own programs. -- How to [use FlatBuffers in C with `flatcc`](@ref flatbuffers_guide_use_c) in your - own programs. -- How to [use the generated Lobster code](@ref flatbuffers_guide_use_lobster) in your - own programs. -- How to [use the generated Rust code](@ref flatbuffers_guide_use_rust) in your - own programs. -- How to [use the generated Swift code](@ref flatbuffers_guide_use_swift) in your - own programs. -- [Support matrix](@ref flatbuffers_support) for platforms/languages/features. -- Some [benchmarks](@ref flatbuffers_benchmarks) showing the advantage of - using FlatBuffers. -- A [white paper](@ref flatbuffers_white_paper) explaining the "why" of - FlatBuffers. -- How to use the [schema-less](@ref flexbuffers) version of - FlatBuffers. -- A description of the [internals](@ref flatbuffers_internals) of FlatBuffers. -- A formal [grammar](@ref flatbuffers_grammar) of the schema language. - -## Online resources - -- [GitHub repository](http://github.com/google/flatbuffers) -- [Landing page](http://google.github.io/flatbuffers) -- [FlatBuffers Google Group](https://groups.google.com/forum/#!forum/flatbuffers) -- [Discord](https://discord.gg/6qgKs3R) and [Gitter](https://gitter.im/lobster_programming_language/community) chat. -- [FlatBuffers Issues Tracker](http://github.com/google/flatbuffers/issues) -- Independent implementations & tools: - - [FlatCC](https://github.com/dvidelabs/flatcc) Alternative FlatBuffers - parser, code generator and runtime all in C. -- Videos: - - Colt's [DevByte](https://www.youtube.com/watch?v=iQTxMkSJ1dQ). - - GDC 2015 [Lightning Talk](https://www.youtube.com/watch?v=olmL1fUnQAQ). - - FlatBuffers for [Go](https://www.youtube.com/watch?v=-BPVId_lA5w). - - Evolution of FlatBuffers - [visualization](https://www.youtube.com/watch?v=a0QE0xS8rKM). -- Useful documentation created by others: - - [FlatBuffers in Go](https://rwinslow.com/tags/flatbuffers/) - - [FlatBuffers in Android](http://frogermcs.github.io/flatbuffers-in-android-introdution/) - - [Parsing JSON to FlatBuffers in Java](http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/) - - [FlatBuffers in Unity](http://exiin.com/blog/flatbuffers-for-unity-sample-code/) - - [FlexBuffers C#](https://github.com/mzaks/FlexBuffers-CSharp) and - [article](https://medium.com/@icex33/flexbuffers-for-unity3d-4d1ab5c53fbe?) - on its use. diff --git a/docs-old/source/FlexBuffers.md b/docs-old/source/FlexBuffers.md deleted file mode 100644 index 974dd693f3f..00000000000 --- a/docs-old/source/FlexBuffers.md +++ /dev/null @@ -1,204 +0,0 @@ -FlexBuffers {#flexbuffers} -========== - -FlatBuffers was designed around schemas, because when you want maximum -performance and data consistency, strong typing is helpful. - -There are however times when you want to store data that doesn't fit a -schema, because you can't know ahead of time what all needs to be stored. - -For this, FlatBuffers has a dedicated format, called FlexBuffers. -This is a binary format that can be used in conjunction -with FlatBuffers (by storing a part of a buffer in FlexBuffers -format), or also as its own independent serialization format. - -While it loses the strong typing, you retain the most unique advantage -FlatBuffers has over other serialization formats (schema-based or not): -FlexBuffers can also be accessed without parsing / copying / object allocation. -This is a huge win in efficiency / memory friendly-ness, and allows unique -use cases such as mmap-ing large amounts of free-form data. - -FlexBuffers' design and implementation allows for a very compact encoding, -combining automatic pooling of strings with automatic sizing of containers to -their smallest possible representation (8/16/32/64 bits). Many values and -offsets can be encoded in just 8 bits. While a schema-less representation is -usually more bulky because of the need to be self-descriptive, FlexBuffers -generates smaller binaries for many cases than regular FlatBuffers. - -FlexBuffers is still slower than regular FlatBuffers though, so we recommend to -only use it if you need it. - - -# Usage in C++ - -Include the header `flexbuffers.h`, which in turn depends on `flatbuffers.h` -and `util.h`. - -To create a buffer: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -flexbuffers::Builder fbb; -fbb.Int(13); -fbb.Finish(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You create any value, followed by `Finish`. Unlike FlatBuffers which requires -the root value to be a table, here any value can be the root, including a lonely -int value. - -You can now access the `std::vector` that contains the encoded value -as `fbb.GetBuffer()`. Write it, send it, or store it in a parent FlatBuffer. In -this case, the buffer is just 3 bytes in size. - -To read this value back, you could just say: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -auto root = flexbuffers::GetRoot(my_buffer); -int64_t i = root.AsInt64(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -FlexBuffers stores ints only as big as needed, so it doesn't differentiate -between different sizes of ints. You can ask for the 64 bit version, -regardless of what you put in. In fact, since you demand to read the root -as an int, if you supply a buffer that actually contains a float, or a -string with numbers in it, it will convert it for you on the fly as well, -or return 0 if it can't. If instead you actually want to know what is inside -the buffer before you access it, you can call `root.GetType()` or `root.IsInt()` -etc. - -Here's a slightly more complex value you could write instead of `fbb.Int` above: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -fbb.Map([&]() { - fbb.Vector("vec", [&]() { - fbb.Int(-100); - fbb.String("Fred"); - fbb.IndirectFloat(4.0f); - }); - fbb.UInt("foo", 100); -}); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This stores the equivalent of the JSON value -`{ vec: [ -100, "Fred", 4.0 ], foo: 100 }`. The root is a dictionary that has -just two key-value pairs, with keys `vec` and `foo`. Unlike FlatBuffers, it -actually has to store these keys in the buffer (which it does only once if -you store multiple such objects, by pooling key values), but also unlike -FlatBuffers it has no restriction on the keys (fields) that you use. - -The map constructor uses a C++11 Lambda to group its children, but you can -also use more conventional start/end calls if you prefer. - -The first value in the map is a vector. You'll notice that unlike FlatBuffers, -you can use mixed types. There is also a `TypedVector` variant that only -allows a single type, and uses a bit less memory. - -`IndirectFloat` is an interesting feature that allows you to store values -by offset rather than inline. Though that doesn't make any visible change -to the user, the consequence is that large values (especially doubles or -64 bit ints) that occur more than once can be shared (see ReuseValue). -Another use case is inside of vectors, where the largest element makes -up the size of all elements (e.g. a single double forces all elements to -64bit), so storing a lot of small integers together with a double is more efficient if the double is indirect. - -Accessing it: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} -auto map = flexbuffers::GetRoot(my_buffer).AsMap(); -map.size(); // 2 -auto vec = map["vec"].AsVector(); -vec.size(); // 3 -vec[0].AsInt64(); // -100; -vec[1].AsString().c_str(); // "Fred"; -vec[1].AsInt64(); // 0 (Number parsing failed). -vec[2].AsDouble(); // 4.0 -vec[2].AsString().IsTheEmptyString(); // true (Wrong Type). -vec[2].AsString().c_str(); // "" (This still works though). -vec[2].ToString().c_str(); // "4" (Or have it converted). -map["foo"].AsUInt8(); // 100 -map["unknown"].IsNull(); // true -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -# Usage in Java - -Java implementation follows the C++ one, closely. - -For creating the equivalent of the same JSON `{ vec: [ -100, "Fred", 4.0 ], foo: 100 }`, -one could use the following code: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} -FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512), - FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); -int smap = builder.startMap(); -int svec = builder.startVector(); -builder.putInt(-100); -builder.putString("Fred"); -builder.putFloat(4.0); -builder.endVector("vec", svec, false, false); -builder.putInt("foo", 100); -builder.endMap(null, smap); -ByteBuffer bb = builder.finish(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Similarly, to read the data, just: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} -FlexBuffers.Map map = FlexBuffers.getRoot(bb).asMap(); -map.size(); // 2 -FlexBuffers.Vector vec = map.get("vec").asVector(); -vec.size(); // 3 -vec.get(0).asLong(); // -100; -vec.get(1).asString(); // "Fred"; -vec.get(1).asLong(); // 0 (Number parsing failed). -vec.get(2).asFloat(); // 4.0 -vec.get(2).asString().isEmpty(); // true (Wrong Type). -vec.get(2).asString(); // "" (This still works though). -vec.get(2).toString(); // "4.0" (Or have it converted). -map.get("foo").asUInt(); // 100 -map.get("unknown").isNull(); // true -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -# Binary encoding - -A description of how FlexBuffers are encoded is in the -[internals](@ref flatbuffers_internals) document. - - -# Nesting inside a FlatBuffer - -You can mark a field as containing a FlexBuffer, e.g. - - a:[ubyte] (flexbuffer); - -A special accessor will be generated that allows you to access the root value -directly, e.g. `a_flexbuffer_root().AsInt64()`. - - -# Efficiency tips - -* Vectors generally are a lot more efficient than maps, so prefer them over maps - when possible for small objects. Instead of a map with keys `x`, `y` and `z`, - use a vector. Better yet, use a typed vector. Or even better, use a fixed - size typed vector. -* Maps are backwards compatible with vectors, and can be iterated as such. - You can iterate either just the values (`map.Values()`), or in parallel with - the keys vector (`map.Keys()`). If you intend - to access most or all elements, this is faster than looking up each element - by key, since that involves a binary search of the key vector. -* When possible, don't mix values that require a big bit width (such as double) - in a large vector of smaller values, since all elements will take on this - width. Use `IndirectDouble` when this is a possibility. Note that - integers automatically use the smallest width possible, i.e. if you ask - to serialize an int64_t whose value is actually small, you will use less - bits. Doubles are represented as floats whenever possible losslessly, but - this is only possible for few values. - Since nested vectors/maps are stored over offsets, they typically don't - affect the vector width. -* To store large arrays of byte data, use a blob. If you'd use a typed - vector, the bit width of the size field may make it use more space than - expected, and may not be compatible with `memcpy`. - Similarly, large arrays of (u)int16_t may be better off stored as a - binary blob if their size could exceed 64k elements. - Construction and use are otherwise similar to strings. diff --git a/docs-old/source/GoApi.md b/docs-old/source/GoApi.md deleted file mode 100644 index 98be2b6a9e4..00000000000 --- a/docs-old/source/GoApi.md +++ /dev/null @@ -1,26 +0,0 @@ -Go API -====== - -\addtogroup flatbuffers_go_api - - -\snippet GoApi_generated.txt Go API diff --git a/docs-old/source/GoApi_generated.txt b/docs-old/source/GoApi_generated.txt deleted file mode 100644 index 3d4e0fc77ae..00000000000 --- a/docs-old/source/GoApi_generated.txt +++ /dev/null @@ -1,125 +0,0 @@ -// This file was generated using `godoc` and customized for use with the -// API Reference documentation. To recreate this file, use the `godoc` tool -// (http://godoc.org) with the files in the `flatbuffers/go` folder. -// -// Note: You may need to ensure that copies of the files exist in the -// `src/` subfolder at the path set by the `$GOROOT` environment variable. -// You can either move the files to `$GOROOT/src/flatbuffers` manually, if -// `$GOROOT` is already set, otherwise you will need to manually set the -// `$GOROOT` variable to a path and create `src/flatbuffers` subfolders at that -// path. Then copy these files into `$GOROOT/src/flatbuffers`. (Some versions of -// `godoc` include a `-path` flag. This could be used instead, if available). -// -// Once the files exist at the `$GOROOT/src/flatbuffers` location, you can -// regenerate this doc using the following command: -// `godoc flatbuffers > GoApi_generated.txt`. -// -// After the documentation is generated, you will have to manually remove any -// non-user facing documentation from this file. - -/// [Go API] -PACKAGE DOCUMENTATION - -package flatbuffers - Package flatbuffers provides facilities to read and write flatbuffers - objects. - -TYPES - -type Builder struct { - // `Bytes` gives raw access to the buffer. Most users will want to use - // FinishedBytes() instead. - Bytes []byte -} - Builder is a state machine for creating FlatBuffer objects. Use a - Builder to construct object(s) starting from leaf nodes. - - A Builder constructs byte buffers in a last-first manner for simplicity - and performance. - -FUNCTIONS - -func NewBuilder(initialSize int) *Builder - NewBuilder initializes a Builder of size `initial_size`. The internal - buffer is grown as needed. - -func (b *Builder) CreateByteString(s []byte) UOffsetT - CreateByteString writes a byte slice as a string (null-terminated). - -func (b *Builder) CreateByteVector(v []byte) UOffsetT - CreateByteVector writes a ubyte vector - -func (b *Builder) CreateString(s string) UOffsetT - CreateString writes a null-terminated string as a vector. - -func (b *Builder) EndVector(vectorNumElems int) UOffsetT - EndVector writes data necessary to finish vector construction. - -func (b *Builder) Finish(rootTable UOffsetT) - Finish finalizes a buffer, pointing to the given `rootTable`. - -func (b *Builder) FinishedBytes() []byte - FinishedBytes returns a pointer to the written data in the byte buffer. - Panics if the builder is not in a finished state (which is caused by - calling `Finish()`). - -func (b *Builder) Head() UOffsetT - Head gives the start of useful data in the underlying byte buffer. Note: - unlike other functions, this value is interpreted as from the left. - -func (b *Builder) PrependBool(x bool) - PrependBool prepends a bool to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependByte(x byte) - PrependByte prepends a byte to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependFloat32(x float32) - PrependFloat32 prepends a float32 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependFloat64(x float64) - PrependFloat64 prepends a float64 to the Builder buffer. Aligns and - checks for space. - -func (b *Builder) PrependInt16(x int16) - PrependInt16 prepends a int16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt32(x int32) - PrependInt32 prepends a int32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt64(x int64) - PrependInt64 prepends a int64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependInt8(x int8) - PrependInt8 prepends a int8 to the Builder buffer. Aligns and checks for - space. - -func (b *Builder) PrependUOffsetT(off UOffsetT) - PrependUOffsetT prepends an UOffsetT, relative to where it will be - written. - -func (b *Builder) PrependUint16(x uint16) - PrependUint16 prepends a uint16 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint32(x uint32) - PrependUint32 prepends a uint32 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint64(x uint64) - PrependUint64 prepends a uint64 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) PrependUint8(x uint8) - PrependUint8 prepends a uint8 to the Builder buffer. Aligns and checks - for space. - -func (b *Builder) Reset() - Reset truncates the underlying Builder buffer, facilitating alloc-free - reuse of a Builder. It also resets bookkeeping data. -/// [Go API] diff --git a/docs-old/source/GoUsage.md b/docs-old/source/GoUsage.md deleted file mode 100644 index e2aa115e81c..00000000000 --- a/docs-old/source/GoUsage.md +++ /dev/null @@ -1,99 +0,0 @@ -Use in Go {#flatbuffers_guide_use_go} -========= - -## Before you get started - -Before diving into the FlatBuffers usage in Go, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Go). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Go. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Go library code location - -The code for the FlatBuffers Go library can be found at -`flatbuffers/go`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/go). - -## Testing the FlatBuffers Go library - -The code to test the Go library can be found at `flatbuffers/tests`. -The test code itself is located in [go_test.go](https://github.com/google/ -flatbuffers/blob/master/tests/go_test.go). - -To run the tests, use the [GoTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/GoTest.sh) shell script. - -*Note: The shell script requires [Go](https://golang.org/doc/install) to -be installed.* - -## Using the FlatBuffers Go library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Go.* - -FlatBuffers supports reading and writing binary FlatBuffers in Go. - -To use FlatBuffers in your own code, first generate Go classes from your -schema with the `--go` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Go: First, -include the library and generated code. Then read a FlatBuffer binary file into -a `[]byte`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} - import ( - example "MyGame/Example" - flatbuffers "github.com/google/flatbuffers/go" - - "os" - ) - - buf, err := os.ReadFile("monster.dat") - // handle err - monster := example.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} - hp := monster.Hp() - pos := monster.Pos(nil) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} - monster := example.GetRootAsMonster(buf, 0) - - // Set table field. - if ok := monster.MutateHp(10); !ok { - panic("failed to mutate Hp") - } - - // Set struct field. - monster.Pos().MutateZ(4) - - // This mutation will fail because the mana field is not available in - // the buffer. It should be set when creating the buffer. - if ok := monster.MutateMana(20); !ok { - panic("failed to mutate Hp") - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The term `mutate` is used instead of `set` to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer. - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Go, though you could use the C++ parser through cgo. Please see the -C++ documentation for more on text parsing. - -
diff --git a/docs-old/source/Grammar.md b/docs-old/source/Grammar.md deleted file mode 100644 index a54f4beae52..00000000000 --- a/docs-old/source/Grammar.md +++ /dev/null @@ -1,74 +0,0 @@ -Grammar of the schema language {#flatbuffers_grammar} -============================== - -schema = include* - ( namespace\_decl | type\_decl | enum\_decl | root\_decl | - file_extension_decl | file_identifier_decl | - attribute\_decl | rpc\_decl | object )* - -include = `include` string\_constant `;` - -namespace\_decl = `namespace` ident ( `.` ident )* `;` - -attribute\_decl = `attribute` ident | `"` ident `"` `;` - -type\_decl = ( `table` | `struct` ) ident metadata `{` field\_decl+ `}` - -enum\_decl = ( `enum` ident `:` type | `union` ident ) metadata `{` -commasep( enumval\_decl ) `}` - -root\_decl = `root_type` ident `;` - -field\_decl = ident `:` type [ `=` scalar ] metadata `;` - -rpc\_decl = `rpc_service` ident `{` rpc\_method+ `}` - -rpc\_method = ident `(` ident `)` `:` ident metadata `;` - -type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` | -`float` | `long` | `ulong` | `double` | -`int8` | `uint8` | `int16` | `uint16` | `int32` | `uint32`| `int64` | `uint64` | -`float32` | `float64` | -`string` | `[` type `]` | ident - -enumval\_decl = ident [ `=` integer\_constant ] metadata - -metadata = [ `(` commasep( ident [ `:` single\_value ] ) `)` ] - -scalar = boolean\_constant | integer\_constant | float\_constant - -object = `{` commasep( ident `:` value ) `}` - -single\_value = scalar | string\_constant - -value = single\_value | object | `[` commasep( value ) `]` - -commasep(x) = [ x ( `,` x )\* ] - -file_extension_decl = `file_extension` string\_constant `;` - -file_identifier_decl = `file_identifier` string\_constant `;` - -string\_constant = `\".*?\"` - -ident = `[a-zA-Z_][a-zA-Z0-9_]*` - -`[:digit:]` = `[0-9]` - -`[:xdigit:]` = `[0-9a-fA-F]` - -dec\_integer\_constant = `[-+]?[:digit:]+` - -hex\_integer\_constant = `[-+]?0[xX][:xdigit:]+` - -integer\_constant = dec\_integer\_constant | hex\_integer\_constant - -dec\_float\_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?` - -hex\_float\_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)` - -special\_float\_constant = `[-+]?(nan|inf|infinity)` - -float\_constant = dec\_float\_constant | hex\_float\_constant | special\_float\_constant - -boolean\_constant = `true` | `false` diff --git a/docs-old/source/IntermediateRepresentation.md b/docs-old/source/IntermediateRepresentation.md deleted file mode 100644 index f4eb0753900..00000000000 --- a/docs-old/source/IntermediateRepresentation.md +++ /dev/null @@ -1,35 +0,0 @@ -# Flatbuffers Intermediate Representation {#intermediate_representation} - -We use [reflection.fbs](https://github.com/google/flatbuffers/blob/master/reflection/reflection.fbs) -as our intermediate representation. `flatc` parses `.fbs` files, checks them for -errors and stores the resulting data in this IR, outputting `.bfbs` files. -Since this IR is a Flatbuffer, you can load and use it at runtime for runtime -reflection purposes. - -There are some quirks: -- Tables and Structs are serialized as `Object`s. -- Unions and Enums are serialized as `Enum`s. -- It is the responsibility of the code generator to check the `advanced_features` - field of `Schema`. These mark the presence of new, backwards incompatible, - schema features. Code generators must error if generating a schema with - unrecognized advanced features. -- Filenames are relative to a "project root" denoted by "//" in the path. This - may be specified in flatc with `--bfbs-filenames=$PROJECT_ROOT`, or it will be - inferred to be the directory containing the first provided schema file. - - -## Invocation -You can invoke it like so -```{.sh} -flatc -b --schema ${your_fbs_files} -``` -This generates `.bfbs` (binary flatbuffer schema) files. - -Some information is not included by default. See the `--bfbs-filenames` and -`--bfbs-comments` flags. These may be necessary for code-generators, so they can -add documentation and maybe name generated files (depending on the generator). - - -TODO(cneo): Flags to output bfbs as flexbuffers or json. - -TODO(cneo): Tutorial for building a flatc plugin. diff --git a/docs-old/source/Internals.md b/docs-old/source/Internals.md deleted file mode 100644 index 591f040c439..00000000000 --- a/docs-old/source/Internals.md +++ /dev/null @@ -1,468 +0,0 @@ -FlatBuffer Internals {#flatbuffers_internals} -==================== - -This section is entirely optional for the use of FlatBuffers. In normal -usage, you should never need the information contained herein. If you're -interested however, it should give you more of an appreciation of why -FlatBuffers is both efficient and convenient. - -### Format components - -A FlatBuffer is a binary file and in-memory format consisting mostly of -scalars of various sizes, all aligned to their own size. Each scalar is -also always represented in little-endian format, as this corresponds to -all commonly used CPUs today. FlatBuffers will also work on big-endian -machines, but will be slightly slower because of additional -byte-swap intrinsics. - -It is assumed that the following conditions are met, to ensure -cross-platform interoperability: -- The binary `IEEE-754` format is used for floating-point numbers. -- The `two's complemented` representation is used for signed integers. -- The endianness is the same for floating-point numbers as for integers. - -On purpose, the format leaves a lot of details about where exactly -things live in memory undefined, e.g. fields in a table can have any -order, and objects to some extent can be stored in many orders. This is -because the format doesn't need this information to be efficient, and it -leaves room for optimization and extension (for example, fields can be -packed in a way that is most compact). Instead, the format is defined in -terms of offsets and adjacency only. This may mean two different -implementations may produce different binaries given the same input -values, and this is perfectly valid. - -### Format identification - -The format also doesn't contain information for format identification -and versioning, which is also by design. FlatBuffers is a statically typed -system, meaning the user of a buffer needs to know what kind of buffer -it is. FlatBuffers can of course be wrapped inside other containers -where needed, or you can use its union feature to dynamically identify -multiple possible sub-objects stored. Additionally, it can be used -together with the schema parser if full reflective capabilities are -desired. - -Versioning is something that is intrinsically part of the format (the -optionality / extensibility of fields), so the format itself does not -need a version number (it's a meta-format, in a sense). We're hoping -that this format can accommodate all data needed. If format breaking -changes are ever necessary, it would become a new kind of format rather -than just a variation. - -### Offsets - -The most important and generic offset type (see `flatbuffers.h`) is -`uoffset_t`, which is currently always a `uint32_t`, and is used to -refer to all tables/unions/strings/vectors (these are never stored -in-line). 32bit is -intentional, since we want to keep the format binary compatible between -32 and 64bit systems, and a 64bit offset would bloat the size for almost -all uses. A version of this format with 64bit (or 16bit) offsets is easy to set -when needed. Unsigned means they can only point in one direction, which -typically is forward (towards a higher memory location). Any backwards -offsets will be explicitly marked as such. - -The format starts with an `uoffset_t` to the root table in the buffer. - -We have two kinds of objects, structs and tables. - -### Structs - -These are the simplest, and as mentioned, intended for simple data that -benefits from being extra efficient and doesn't need versioning / -extensibility. They are always stored inline in their parent (a struct, -table, or vector) for maximum compactness. Structs define a consistent -memory layout where all components are aligned to their size, and -structs aligned to their largest scalar member. This is done independent -of the alignment rules of the underlying compiler to guarantee a cross -platform compatible layout. This layout is then enforced in the generated -code. - -### Tables - -Unlike structs, these are not stored in inline in their parent, but are -referred to by offset. - -They start with an `soffset_t` to a vtable. This is a signed version of -`uoffset_t`, since vtables may be stored anywhere relative to the object. -This offset is subtracted (not added) from the object start to arrive at -the vtable start. This offset is followed by all the -fields as aligned scalars (or offsets). Unlike structs, not all fields -need to be present. There is no set order and layout. A table may contain -field offsets that point to the same value if the user explicitly -serializes the same offset twice. - -To be able to access fields regardless of these uncertainties, we go -through a vtable of offsets. Vtables are shared between any objects that -happen to have the same vtable values. - -The elements of a vtable are all of type `voffset_t`, which is -a `uint16_t`. The first element is the size of the vtable in bytes, -including the size element. The second one is the size of the object, in bytes -(including the vtable offset). This size could be used for streaming, to know -how many bytes to read to be able to access all *inline* fields of the object. -The remaining elements are the N offsets, where N is the amount of fields -declared in the schema when the code that constructed this buffer was -compiled (thus, the size of the table is N + 2). - -All accessor functions in the generated code for tables contain the -offset into this table as a constant. This offset is checked against the -first field (the number of elements), to protect against newer code -reading older data. If this offset is out of range, or the vtable entry -is 0, that means the field is not present in this object, and the -default value is return. Otherwise, the entry is used as offset to the -field to be read. - -### Unions - -Unions are encoded as the combination of two fields: an enum representing the -union choice and the offset to the actual element. FlatBuffers reserves the -enumeration constant `NONE` (encoded as 0) to mean that the union field is not -set. - -### Strings and Vectors - -Strings are simply a vector of bytes, and are always -null-terminated. Vectors are stored as contiguous aligned scalar -elements prefixed by a 32bit element count (not including any -null termination). Neither is stored inline in their parent, but are referred to -by offset. A vector may consist of more than one offset pointing to the same -value if the user explicitly serializes the same offset twice. - -### Construction - -The current implementation constructs these buffers backwards (starting -at the highest memory address of the buffer), since -that significantly reduces the amount of bookkeeping and simplifies the -construction API. - -### Code example - -Here's an example of the code that gets generated for the `samples/monster.fbs`. -What follows is the entire file, broken up by comments: - - // automatically generated, do not modify - - #include "flatbuffers/flatbuffers.h" - - namespace MyGame { - namespace Sample { - -Nested namespace support. - - enum { - Color_Red = 0, - Color_Green = 1, - Color_Blue = 2, - }; - - inline const char **EnumNamesColor() { - static const char *names[] = { "Red", "Green", "Blue", nullptr }; - return names; - } - - inline const char *EnumNameColor(int e) { return EnumNamesColor()[e]; } - -Enums and convenient reverse lookup. - - enum { - Any_NONE = 0, - Any_Monster = 1, - }; - - inline const char **EnumNamesAny() { - static const char *names[] = { "NONE", "Monster", nullptr }; - return names; - } - - inline const char *EnumNameAny(int e) { return EnumNamesAny()[e]; } - -Unions share a lot with enums. - - struct Vec3; - struct Monster; - -Predeclare all data types since circular references between types are allowed -(circular references between object are not, though). - - FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vec3 { - private: - float x_; - float y_; - float z_; - - public: - Vec3(float x, float y, float z) - : x_(flatbuffers::EndianScalar(x)), y_(flatbuffers::EndianScalar(y)), z_(flatbuffers::EndianScalar(z)) {} - - float x() const { return flatbuffers::EndianScalar(x_); } - float y() const { return flatbuffers::EndianScalar(y_); } - float z() const { return flatbuffers::EndianScalar(z_); } - }; - FLATBUFFERS_STRUCT_END(Vec3, 12); - -These ugly macros do a couple of things: they turn off any padding the compiler -might normally do, since we add padding manually (though none in this example), -and they enforce alignment chosen by FlatBuffers. This ensures the layout of -this struct will look the same regardless of compiler and platform. Note that -the fields are private: this is because these store little endian scalars -regardless of platform (since this is part of the serialized data). -`EndianScalar` then converts back and forth, which is a no-op on all current -mobile and desktop platforms, and a single machine instruction on the few -remaining big endian platforms. - - struct Monster : private flatbuffers::Table { - const Vec3 *pos() const { return GetStruct(4); } - int16_t mana() const { return GetField(6, 150); } - int16_t hp() const { return GetField(8, 100); } - const flatbuffers::String *name() const { return GetPointer(10); } - const flatbuffers::Vector *inventory() const { return GetPointer *>(14); } - int8_t color() const { return GetField(16, 2); } - }; - -Tables are a bit more complicated. A table accessor struct is used to point at -the serialized data for a table, which always starts with an offset to its -vtable. It derives from `Table`, which contains the `GetField` helper functions. -GetField takes a vtable offset, and a default value. It will look in the vtable -at that offset. If the offset is out of bounds (data from an older version) or -the vtable entry is 0, the field is not present and the default is returned. -Otherwise, it uses the entry as an offset into the table to locate the field. - - struct MonsterBuilder { - flatbuffers::FlatBufferBuilder &fbb_; - flatbuffers::uoffset_t start_; - void add_pos(const Vec3 *pos) { fbb_.AddStruct(4, pos); } - void add_mana(int16_t mana) { fbb_.AddElement(6, mana, 150); } - void add_hp(int16_t hp) { fbb_.AddElement(8, hp, 100); } - void add_name(flatbuffers::Offset name) { fbb_.AddOffset(10, name); } - void add_inventory(flatbuffers::Offset> inventory) { fbb_.AddOffset(14, inventory); } - void add_color(int8_t color) { fbb_.AddElement(16, color, 2); } - MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } - flatbuffers::Offset Finish() { return flatbuffers::Offset(fbb_.EndTable(start_, 7)); } - }; - -`MonsterBuilder` is the base helper struct to construct a table using a -`FlatBufferBuilder`. You can add the fields in any order, and the `Finish` -call will ensure the correct vtable gets generated. - - inline flatbuffers::Offset CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, - const Vec3 *pos, int16_t mana, - int16_t hp, - flatbuffers::Offset name, - flatbuffers::Offset> inventory, - int8_t color) { - MonsterBuilder builder_(_fbb); - builder_.add_inventory(inventory); - builder_.add_name(name); - builder_.add_pos(pos); - builder_.add_hp(hp); - builder_.add_mana(mana); - builder_.add_color(color); - return builder_.Finish(); - } - -`CreateMonster` is a convenience function that calls all functions in -`MonsterBuilder` above for you. Note that if you pass values which are -defaults as arguments, it will not actually construct that field, so -you can probably use this function instead of the builder class in -almost all cases. - - inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot(buf); } - -This function is only generated for the root table type, to be able to -start traversing a FlatBuffer from a raw buffer pointer. - - }; // namespace MyGame - }; // namespace Sample - -### Encoding example. - -Below is a sample encoding for the following JSON corresponding to the above -schema: - - { pos: { x: 1, y: 2, z: 3 }, name: "fred", hp: 50 } - -Resulting in this binary buffer: - - // Start of the buffer: - uint32_t 20 // Offset to the root table. - - // Start of the vtable. Not shared in this example, but could be: - uint16_t 16 // Size of table, starting from here. - uint16_t 22 // Size of object inline data. - uint16_t 4, 0, 20, 16, 0, 0 // Offsets to fields from start of (root) table, 0 for not present. - - // Start of the root table: - int32_t 16 // Offset to vtable used (default negative direction) - float 1, 2, 3 // the Vec3 struct, inline. - uint32_t 8 // Offset to the name string. - int16_t 50 // hp field. - int16_t 0 // Padding for alignment. - - // Start of name string: - uint32_t 4 // Length of string. - int8_t 'f', 'r', 'e', 'd', 0, 0, 0, 0 // Text + 0 termination + padding. - -Note that this not the only possible encoding, since the writer has some -flexibility in which of the children of root object to write first (though in -this case there's only one string), and what order to write the fields in. -Different orders may also cause different alignments to happen. - -### Additional reading. - -The author of the C language implementation has made a similar -[document](https://github.com/dvidelabs/flatcc/blob/master/doc/binary-format.md#flatbuffers-binary-format) -that may further help clarify the format. - -# FlexBuffers - -The [schema-less](@ref flexbuffers) version of FlatBuffers have their -own encoding, detailed here. - -It shares many properties mentioned above, in that all data is accessed -over offsets, all scalars are aligned to their own size, and -all data is always stored in little endian format. - -One difference is that FlexBuffers are built front to back, so children are -stored before parents, and the root of the data starts at the last byte. - -Another difference is that scalar data is stored with a variable number of bits -(8/16/32/64). The current width is always determined by the *parent*, i.e. if -the scalar sits in a vector, the vector determines the bit width for all -elements at once. Selecting the minimum bit width for a particular vector is -something the encoder does automatically and thus is typically of no concern -to the user, though being aware of this feature (and not sticking a double in -the same vector as a bunch of byte sized elements) is helpful for efficiency. - -Unlike FlatBuffers there is only one kind of offset, and that is an unsigned -integer indicating the number of bytes in a negative direction from the address -of itself (where the offset is stored). - -### Vectors - -The representation of the vector is at the core of how FlexBuffers works (since -maps are really just a combination of 2 vectors), so it is worth starting there. - -As mentioned, a vector is governed by a single bit width (supplied by its -parent). This includes the size field. For example, a vector that stores the -integer values `1, 2, 3` is encoded as follows: - - uint8_t 3, 1, 2, 3, 4, 4, 4 - -The first `3` is the size field, and is placed before the vector (an offset -from the parent to this vector points to the first element, not the size -field, so the size field is effectively at index -1). -Since this is an untyped vector `SL_VECTOR`, it is followed by 3 type -bytes (one per element of the vector), which are always following the vector, -and are always a uint8_t even if the vector is made up of bigger scalars. - -A vector may include more than one offset pointing to the same value if the -user explicitly serializes the same offset twice. - -### Types - -A type byte is made up of 2 components (see flexbuffers.h for exact values): - -* 2 lower bits representing the bit-width of the child (8, 16, 32, 64). - This is only used if the child is accessed over an offset, such as a child - vector. It is ignored for inline types. -* 6 bits representing the actual type (see flexbuffers.h). - -Thus, in this example `4` means 8 bit child (value 0, unused, since the value is -in-line), type `SL_INT` (value 1). - -### Typed Vectors - -These are like the Vectors above, but omit the type bytes. The type is instead -determined by the vector type supplied by the parent. Typed vectors are only -available for a subset of types for which these savings can be significant, -namely inline signed/unsigned integers (`TYPE_VECTOR_INT` / `TYPE_VECTOR_UINT`), -floats (`TYPE_VECTOR_FLOAT`), and keys (`TYPE_VECTOR_KEY`, see below). - -Additionally, for scalars, there are fixed length vectors of sizes 2 / 3 / 4 -that don't store the size (`TYPE_VECTOR_INT2` etc.), for an additional savings -in space when storing common vector or color data. - -### Scalars - -FlexBuffers supports integers (`TYPE_INT` and `TYPE_UINT`) and floats -(`TYPE_FLOAT`), available in the bit-widths mentioned above. They can be stored -both inline and over an offset (`TYPE_INDIRECT_*`). - -The offset version is useful to encode costly 64bit (or even 32bit) quantities -into vectors / maps of smaller sizes, and to share / repeat a value multiple -times. - -### Booleans and Nulls - -Booleans (`TYPE_BOOL`) and nulls (`TYPE_NULL`) are encoded as inlined unsigned integers. - -### Blobs, Strings and Keys. - -A blob (`TYPE_BLOB`) is encoded similar to a vector, with one difference: the -elements are always `uint8_t`. The parent bit width only determines the width of -the size field, allowing blobs to be large without the elements being large. - -Strings (`TYPE_STRING`) are similar to blobs, except they have an additional 0 -termination byte for convenience, and they MUST be UTF-8 encoded (since an -accessor in a language that does not support pointers to UTF-8 data may have to -convert them to a native string type). - -A "Key" (`TYPE_KEY`) is similar to a string, but doesn't store the size -field. They're so named because they are used with maps, which don't care -for the size, and can thus be even more compact. Unlike strings, keys cannot -contain bytes of value 0 as part of their data (size can only be determined by -`strlen`), so while you can use them outside the context of maps if you so -desire, you're usually better off with strings. - -### Maps - -A map (`TYPE_MAP`) is like an (untyped) vector, but with 2 prefixes before the -size field: - -| index | field | -| ----: | :----------------------------------------------------------- | -| -3 | An offset to the keys vector (may be shared between tables). | -| -2 | Byte width of the keys vector. | -| -1 | Size (from here on it is compatible with `TYPE_VECTOR`) | -| 0 | Elements. | -| Size | Types. | - -Since a map is otherwise the same as a vector, it can be iterated like -a vector (which is probably faster than lookup by key). - -The keys vector is a typed vector of keys. Both the keys and corresponding -values *have* to be stored in sorted order (as determined by `strcmp`), such -that lookups can be made using binary search. - -The reason the key vector is a separate structure from the value vector is -such that it can be shared between multiple value vectors, and also to -allow it to be treated as its own individual vector in code. - -An example map { foo: 13, bar: 14 } would be encoded as: - - 0 : uint8_t 'b', 'a', 'r', 0 - 4 : uint8_t 'f', 'o', 'o', 0 - 8 : uint8_t 2 // key vector of size 2 - // key vector offset points here - 9 : uint8_t 9, 6 // offsets to bar_key and foo_key - 11: uint8_t 2, 1 // offset to key vector, and its byte width - 13: uint8_t 2 // value vector of size - // value vector offset points here - 14: uint8_t 14, 13 // values - 16: uint8_t 4, 4 // types - -### The root - -As mentioned, the root starts at the end of the buffer. -The last uint8_t is the width in bytes of the root (normally the parent -determines the width, but the root has no parent). The uint8_t before this is -the type of the root, and the bytes before that are the root value (of the -number of bytes specified by the last byte). - -So for example, the integer value `13` as root would be: - - uint8_t 13, 4, 1 // Value, type, root byte width. - - -
diff --git a/docs-old/source/JavaScriptUsage.md b/docs-old/source/JavaScriptUsage.md deleted file mode 100644 index 64764e21619..00000000000 --- a/docs-old/source/JavaScriptUsage.md +++ /dev/null @@ -1,93 +0,0 @@ -Use in JavaScript {#flatbuffers_guide_use_javascript} -================= - -## Before you get started - -Before diving into the FlatBuffers usage in JavaScript, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including JavaScript). This page is specifically designed to cover the nuances -of FlatBuffers usage in JavaScript. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers JavaScript library code location - -The generated code for the FlatBuffers JavaScript library can be found at -https://www.npmjs.com/package/flatbuffers. To use it from sources: - -1. Run `npm run compile` from the main folder to generate JS files from TS. -1. In your project, install it as a normal dependency, using the flatbuffers -folder as the source. - -## Using the FlatBuffers JavaScript library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers.* - -Due to the complexity related with large amounts of JS flavors and module types, -native JS support has been replaced in 2.0 by transpilation from TypeScript. - -Please look at [TypeScript usage](@ref flatbuffers_guide_use_typescript) and -transpile your sources to desired JS flavor. The minimal steps to get up and -running with JS are: - -1. Generate TS files from `*.fbs` by using the `--ts` option. -1. Transpile resulting TS files to desired JS flavor using `tsc` (see - https://www.typescriptlang.org/download for installation instructions). - -~~~{.js} - // Note: These require functions are an example - use your desired module flavor. - var fs = require('fs'); - - var flatbuffers = require('../flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; - - var data = new Uint8Array(fs.readFileSync('monster.dat')); - var buf = new flatbuffers.ByteBuffer(data); - - var monster = MyGame.Example.Monster.getRootAsMonster(buf); - - //--------------------------------------------------------------------------// - - // Note: This code is an example of browser-based HTML/JavaScript. See above - // for the code using JavaScript module loaders (e.g. Node.js). - - - - - // Open the HTML file in a browser and select "monster.dat" from with the - // field. - -~~~ - -Now you can access values like this: - -~~~{.js} - var hp = monster.hp(); - var pos = monster.pos(); -~~~ - -## Text parsing FlatBuffers in JavaScript - -There currently is no support for parsing text (Schema's and JSON) directly -from JavaScript. diff --git a/docs-old/source/JavaUsage.md b/docs-old/source/JavaUsage.md deleted file mode 100644 index 30ba06133ef..00000000000 --- a/docs-old/source/JavaUsage.md +++ /dev/null @@ -1,114 +0,0 @@ -Use in Java {#flatbuffers_guide_use_java} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Java, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages (including Java). -This page is designed to cover the nuances of FlatBuffers usage, -specific to Java. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Java code location - -The code for the FlatBuffers Java library can be found at -`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -java/com/google/flatbuffers). - -## Testing the FlatBuffers Java libraries - -The code to test the libraries can be found at `flatbuffers/tests`. - -The test code for Java is located in [JavaTest.java](https://github.com/google -/flatbuffers/blob/master/tests/JavaTest.java). - -To run the tests, use either [JavaTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/JavaTest.sh) or [JavaTest.bat](https://github.com/ -google/flatbuffers/blob/master/tests/JavaTest.bat), depending on your operating -system. - -*Note: These scripts require that [Java](https://www.oracle.com/java/index.html) -is installed.* - -## Using the FlatBuffers Java library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Java.* - -FlatBuffers supports reading and writing binary FlatBuffers in Java. - -To use FlatBuffers in your own code, first generate Java classes from your -schema with the `--java` option to `flatc`. -Then you can include both FlatBuffers and the generated code to read -or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Java: -First, import the library and generated code. Then, you read a FlatBuffer binary -file into a `byte[]`. You then turn the `byte[]` into a `ByteBuffer`, which you -pass to the `getRootAsMyRootType` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} - import MyGame.Example.*; - import com.google.flatbuffers.FlatBufferBuilder; - - // This snippet ignores exceptions for brevity. - File file = new File("monsterdata_test.mon"); - RandomAccessFile f = new RandomAccessFile(file, "r"); - byte[] data = new byte[(int)f.length()]; - f.readFully(data); - f.close(); - - ByteBuffer bb = ByteBuffer.wrap(data); - Monster monster = Monster.getRootAsMonster(bb); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access the data from the `Monster monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} - short hp = monster.hp(); - Vec3 pos = monster.pos(); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Storing dictionaries in a FlatBuffer - -FlatBuffers doesn't support dictionaries natively, but there is support to -emulate their behavior with vectors and binary search, which means you -can have fast lookups directly from a FlatBuffer without having to unpack -your data into a `Dictionary` or similar. - -To use it: -- Designate one of the fields in a table as the "key" field. You do this - by setting the `key` attribute on this field, e.g. - `name:string (key)`. - You may only have one key field, and it must be of string or scalar type. -- Write out tables of this type as usual, collect their offsets in an - array. -- Instead of calling standard generated method, - e.g.: `Monster.createTestarrayoftablesVector`, - call `createSortedVectorOfTables` (from the `FlatBufferBuilder` object). - which will first sort all offsets such that the tables they refer to - are sorted by the key field, then serialize it. -- Now when you're accessing the FlatBuffer, you can use - the `ByKey` accessor to access elements of the vector, e.g.: - `monster.testarrayoftablesByKey("Frodo")`. - which returns an object of the corresponding table type, - or `null` if not found. - `ByKey` performs a binary search, so should have a similar - speed to `Dictionary`, though may be faster because of better caching. - `ByKey` only works if the vector has been sorted, it will - likely not find elements if it hasn't been sorted. - -## Text parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Java, though you could use the C++ parser through native call -interfaces available to each language. Please see the -C++ documentation for more on text parsing. - -
diff --git a/docs-old/source/KotlinUsage.md b/docs-old/source/KotlinUsage.md deleted file mode 100644 index 092fcd7f5b2..00000000000 --- a/docs-old/source/KotlinUsage.md +++ /dev/null @@ -1,84 +0,0 @@ -Use in Kotlin {#flatbuffers_guide_use_kotlin} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Kotlin, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages (including K). - -This page is designed to cover the nuances of FlatBuffers usage, specific to Kotlin. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## Kotlin and FlatBuffers Java code location - -Code generated for Kotlin currently uses the flatbuffers java runtime library. That means that Kotlin generated code can only have Java virtual machine as target architecture (which includes Android). Kotlin Native and Kotlin.js are currently not supported. - -The code for the FlatBuffers Java library can be found at -`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -java/com/google/flatbuffers). - -## Testing FlatBuffers Kotlin - -The test code for Java is located in [KotlinTest.java](https://github.com/google -/flatbuffers/blob/master/tests/KotlinTest.kt). - -To run the tests, use [KotlinTest.sh](https://github.com/google/ -flatbuffers/blob/master/tests/KotlinTest.sh) shell script. - -*Note: These scripts require that [Kotlin](https://kotlinlang.org/) is installed.* - -## Using the FlatBuffers Kotlin library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Kotlin.* - -FlatBuffers supports reading and writing binary FlatBuffers in Kotlin. - -To use FlatBuffers in your own code, first generate Java classes from your -schema with the `--kotlin` option to `flatc`. -Then you can include both FlatBuffers and the generated code to read -or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Kotlin: -First, import the library and generated code. Then, you read a FlatBuffer binary -file into a `ByteArray`. You then turn the `ByteArray` into a `ByteBuffer`, which you -pass to the `getRootAsMyRootType` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} - import MyGame.Example.* - import com.google.flatbuffers.FlatBufferBuilder - - // This snippet ignores exceptions for brevity. - val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use { - val temp = ByteArray(it.length().toInt()) - it.readFully(temp) - temp - } - - val bb = ByteBuffer.wrap(data) - val monster = Monster.getRootAsMonster(bb) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access the data from the `Monster monster`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} - val hp = monster.hp - val pos = monster.pos!!; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -## Differences between Kotlin and Java code - -Kotlin generated code was designed to be as close as possible to the java counterpart, as for now, we only support kotlin on java virtual machine. So the differences in implementation and usage are basically the ones introduced by the Kotlin language itself. You can find more in-depth information [here](https://kotlinlang.org/docs/reference/comparison-to-java.html). - -The most obvious ones are: - -* Fields as accessed as Kotlin [properties](https://kotlinlang.org/docs/reference/properties.html) -* Static methods are accessed in [companion object](https://kotlinlang.org/docs/reference/classes.html#companion-objects) \ No newline at end of file diff --git a/docs-old/source/LobsterUsage.md b/docs-old/source/LobsterUsage.md deleted file mode 100644 index 723966be79f..00000000000 --- a/docs-old/source/LobsterUsage.md +++ /dev/null @@ -1,85 +0,0 @@ -Use in Lobster {#flatbuffers_guide_use_lobster} -============== - -## Before you get started - -Before diving into the FlatBuffers usage in Lobster, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Lobster). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Lobster. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Lobster library code location - -The code for the FlatBuffers Lobster library can be found at -`flatbuffers/lobster`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -lobster). - -## Testing the FlatBuffers Lobster library - -The code to test the Lobster library can be found at `flatbuffers/tests`. -The test code itself is located in [lobstertest.lobster](https://github.com/google/ -flatbuffers/blob/master/tests/lobstertest.lobster). - -To run the tests, run `lobster lobstertest.lobster`. To obtain Lobster itself, -go to the [Lobster homepage](http://strlen.com/lobster) or -[github](https://github.com/aardappel/lobster) to learn how to build it for your -platform. - -## Using the FlatBuffers Lobster library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Lobster.* - -There is support for both reading and writing FlatBuffers in Lobster. - -To use FlatBuffers in your own code, first generate Lobster classes from your -schema with the `--lobster` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Lobster: -First, import the library and the generated code. Then read a FlatBuffer binary -file into a string, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} - include "monster_generated.lobster" - - let fb = read_file("monsterdata_test.mon") - assert fb - let monster = MyGame_Example_GetRootAsMonster(fb) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} - let hp = monster.hp - let pos = monster.pos -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As you can see, even though `hp` and `pos` are functions that access FlatBuffer -data in-place in the string buffer, they appear as field accesses. - -## Speed - -Using FlatBuffers in Lobster should be relatively fast, as the implementation -makes use of native support for writing binary values, and access of vtables. -Both generated code and the runtime library are therefore small and fast. - -Actual speed will depend on whether you use Lobster as bytecode VM or compiled to -C++. - -## Text Parsing - -Lobster has full support for parsing JSON into FlatBuffers, or generating -JSON from FlatBuffers. See `samples/sample_test.lobster` for an example. - -This uses the C++ parser and generator underneath, so should be both fast and -conformant. - -
diff --git a/docs-old/source/LuaUsage.md b/docs-old/source/LuaUsage.md deleted file mode 100644 index 43c370f5d55..00000000000 --- a/docs-old/source/LuaUsage.md +++ /dev/null @@ -1,81 +0,0 @@ -Use in Lua {#flatbuffers_guide_use_lua} -============= - -## Before you get started - -Before diving into the FlatBuffers usage in Lua, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Lua). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Lua. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Lua library code location - -The code for the FlatBuffers Lua library can be found at -`flatbuffers/lua`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/lua). - -## Testing the FlatBuffers Lua library - -The code to test the Lua library can be found at `flatbuffers/tests`. -The test code itself is located in [luatest.lua](https://github.com/google/ -flatbuffers/blob/master/tests/luatest.lua). - -To run the tests, use the [LuaTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/LuaTest.sh) shell script. - -*Note: This script requires [Lua 5.3](https://www.lua.org/) and -[LuaJIT](http://luajit.org/) to be installed.* - -## Using the FlatBuffers Lua library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Lua.* - -There is support for both reading and writing FlatBuffers in Lua. - -To use FlatBuffers in your own code, first generate Lua classes from your -schema with the `--lua` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Lua: -First, require the module and the generated code. Then read a FlatBuffer binary -file into a `string`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} - -- require the library - local flatbuffers = require("flatbuffers") - - -- require the generated code - local monster = require("MyGame.Sample.Monster") - - -- read the flatbuffer from a file into a string - local f = io.open('monster.dat', 'rb') - local buf = f:read('*a') - f:close() - - -- parse the flatbuffer to get an instance to the root monster - local monster1 = monster.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} - -- use the : notation to access member data - local hp = monster1:Hp() - local pos = monster1:Pos() -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Lua, though you could use the C++ parser through SWIG or ctypes. Please -see the C++ documentation for more on text parsing. - -
diff --git a/docs-old/source/PHPUsage.md b/docs-old/source/PHPUsage.md deleted file mode 100644 index cdff44954dd..00000000000 --- a/docs-old/source/PHPUsage.md +++ /dev/null @@ -1,89 +0,0 @@ -Use in PHP {#flatbuffers_guide_use_php} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in PHP, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including PHP). This page is specifically designed to cover the nuances of -FlatBuffers usage in PHP. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers PHP library code location - -The code for FlatBuffers PHP library can be found at `flatbuffers/php`. You -can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/php). - -## Testing the FlatBuffers JavaScript library - -The code to test the PHP library can be found at `flatbuffers/tests`. -The test code itself is located in [phpTest.php](https://github.com/google/ -flatbuffers/blob/master/tests/phpTest.php). - -You can run the test with `php phpTest.php` from the command line. - -*Note: The PHP test file requires -[PHP](http://php.net/manual/en/install.php) to be installed.* - -## Using theFlatBuffers PHP library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in PHP.* - -FlatBuffers supports both reading and writing FlatBuffers in PHP. - -To use FlatBuffers in your own code, first generate PHP classes from your schema -with the `--php` option to `flatc`. Then you can include both FlatBuffers and -the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in PHP: -First, include the library and generated code (using the PSR `autoload` -function). Then you can read a FlatBuffer binary file, which you -pass the contents of to the `GetRootAsMonster` function: - -~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "tests", "MyGame", "Example"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - - // Read the contents of the FlatBuffer binary file. - $filename = "monster.dat"; - $handle = fopen($filename, "rb"); - $contents = $fread($handle, filesize($filename)); - fclose($handle); - - // Pass the contents to `GetRootAsMonster`. - $monster = \MyGame\Example\Monster::GetRootAsMonster($contents); -~~~ - -Now you can access values like this: - -~~~{.php} - $hp = $monster->GetHp(); - $pos = $monster->GetPos(); -~~~ - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from PHP. diff --git a/docs-old/source/PythonUsage.md b/docs-old/source/PythonUsage.md deleted file mode 100644 index f338cda4368..00000000000 --- a/docs-old/source/PythonUsage.md +++ /dev/null @@ -1,100 +0,0 @@ -Use in Python {#flatbuffers_guide_use_python} -============= - -## Before you get started - -Before diving into the FlatBuffers usage in Python, it should be noted that the -[Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to general -FlatBuffers usage in all of the supported languages (including Python). This -page is designed to cover the nuances of FlatBuffers usage, specific to -Python. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Python library code location - -The code for the FlatBuffers Python library can be found at -`flatbuffers/python/flatbuffers`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ -python). - -## Testing the FlatBuffers Python library - -The code to test the Python library can be found at `flatbuffers/tests`. -The test code itself is located in [py_test.py](https://github.com/google/ -flatbuffers/blob/master/tests/py_test.py). - -To run the tests, use the [PythonTest.sh](https://github.com/google/flatbuffers/ -blob/master/tests/PythonTest.sh) shell script. - -*Note: This script requires [python](https://www.python.org/) to be -installed.* - -## Using the FlatBuffers Python library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Python.* - -There is support for both reading and writing FlatBuffers in Python. - -To use FlatBuffers in your own code, first generate Python classes from your -schema with the `--python` option to `flatc`. Then you can include both -FlatBuffers and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in Python: -First, import the library and the generated code. Then read a FlatBuffer binary -file into a `bytearray`, which you pass to the `GetRootAsMonster` function: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - import MyGame.Example as example - import flatbuffers - - buf = open('monster.dat', 'rb').read() - buf = bytearray(buf) - monster = example.GetRootAsMonster(buf, 0) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - hp = monster.Hp() - pos = monster.Pos() -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Support for Numpy arrays - -The Flatbuffers python library also has support for accessing scalar -vectors as numpy arrays. This can be orders of magnitude faster than -iterating over the vector one element at a time, and is particularly -useful when unpacking large nested flatbuffers. The generated code for -a scalar vector will have a method `AsNumpy()`. In the -case of the Monster example, you could access the inventory vector -like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - inventory = monster.InventoryAsNumpy() - # inventory is a numpy array of type np.dtype('uint8') -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -instead of - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} - inventory = [] - for i in range(monster.InventoryLength()): - inventory.append(int(monster.Inventory(i))) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Numpy is not a requirement. If numpy is not installed on your system, -then attempting to access one of the `*asNumpy()` methods will result -in a `NumpyRequiredForThisFeature` exception. - -## Text Parsing - -There currently is no support for parsing text (Schema's and JSON) directly -from Python, though you could use the C++ parser through SWIG or ctypes. Please -see the C++ documentation for more on text parsing. - -
diff --git a/docs-old/source/README_TO_GENERATE_DOCS.md b/docs-old/source/README_TO_GENERATE_DOCS.md deleted file mode 100644 index 92db87c3423..00000000000 --- a/docs-old/source/README_TO_GENERATE_DOCS.md +++ /dev/null @@ -1,32 +0,0 @@ -## Prerequisites - -To generate the docs for FlatBuffers from the source files, you -will first need to install two programs. - -1. You will need to install `doxygen`. See - [Download Doxygen](https://doxygen.nl/download.html). - -2. You will need to install `doxypypy` to format python comments appropriately. - Install it from [here](https://github.com/Feneric/doxypypy). - -*Note: You will need both `doxygen` and `doxypypy` to be in your -[PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable.* - -After you have both of those files installed and in your path, you need to -set up the `py_filter` to invoke `doxypypy` from `doxygen`. - -Follow the steps -[here](https://github.com/Feneric/doxypypy#invoking-doxypypy-from-doxygen). - -## Generating Docs - -Run the following commands to generate the docs: - -`cd flatbuffers/docs/source` -`doxygen` - -The output is placed in `flatbuffers/docs/html`. - -*Note: The Go API Reference code must be generated ahead of time. For -instructions on how to regenerated this file, please read the comments -in `GoApi.md`.* diff --git a/docs-old/source/RustUsage.md b/docs-old/source/RustUsage.md deleted file mode 100644 index 2a162588a6f..00000000000 --- a/docs-old/source/RustUsage.md +++ /dev/null @@ -1,186 +0,0 @@ -Use in Rust {#flatbuffers_guide_use_rust} -========== - -## Before you get started - -Before diving into the FlatBuffers usage in Rust, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Rust). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Rust. - -#### Prerequisites - -This page assumes you have written a FlatBuffers schema and compiled it -with the Schema Compiler. If you have not, please see -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -and [Writing a schema](@ref flatbuffers_guide_writing_schema). - -Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't -matter), you've generated a Rust file called `mygame_generated.rs` using the -compiler (e.g. `flatc --rust mygame.fbs` or via helpers listed in "Useful -tools created by others" section bellow), you can now start using this in -your program by including the file. As noted, this header relies on the crate -`flatbuffers`, which should be in your include `Cargo.toml`. - -## FlatBuffers Rust library code location - -The code for the FlatBuffers Rust library can be found at -`flatbuffers/rust`. You can browse the library code on the -[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/rust). - -## Testing the FlatBuffers Rust library - -The code to test the Rust library can be found at `flatbuffers/tests/rust_usage_test`. -The test code itself is located in -[integration_test.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/tests/integration_test.rs) - -This test file requires `flatc` to be present. To review how to build the project, -please read the [Building](@ref flatbuffers_guide_building) documentation. - -To run the tests, execute `RustTest.sh` from the `flatbuffers/tests` directory. -For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply -run: `cd tests && ./RustTest.sh`. - -*Note: The shell script requires [Rust](https://www.rust-lang.org) to -be installed.* - -## Using the FlatBuffers Rust library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Rust.* - -FlatBuffers supports both reading and writing FlatBuffers in Rust. - -To use FlatBuffers in your code, first generate the Rust modules from your -schema with the `--rust` option to `flatc`. Then you can import both FlatBuffers -and the generated code to read or write FlatBuffers. - -For example, here is how you would read a FlatBuffer binary file in Rust: -First, include the library and generated code. Then read the file into -a `u8` vector, which you pass, as a byte slice, to `root_as_monster()`. - -This full example program is available in the Rust test suite: -[monster_example.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/bin/monster_example.rs) - -It can be run by `cd`ing to the `rust_usage_test` directory and executing: `cargo run monster_example`. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - extern crate flatbuffers; - - #[allow(dead_code, unused_imports)] - #[path = "../../monster_test_generated.rs"] - mod monster_test_generated; - pub use monster_test_generated::my_game; - - use std::io::Read; - - fn main() { - let mut f = std::fs::File::open("../monsterdata_test.mon").unwrap(); - let mut buf = Vec::new(); - f.read_to_end(&mut buf).expect("file reading failed"); - - let monster = my_game::example::root_as_monster(&buf[..]); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`monster` is of type `Monster`, and points to somewhere *inside* your -buffer (root object pointers are not the same as `buffer_pointer` !). -If you look in your generated header, you'll see it has -convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} - println!("{}", monster.hp()); // `80` - println!("{}", monster.mana()); // default value of `150` - println!("{:?}", monster.name()); // Some("MyMonster") - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -*Note: That we never stored a `mana` value, so it will return the default.* - -## Direct memory access - -As you can see from the above examples, all elements in a buffer are -accessed through generated accessors. This is because everything is -stored in little endian format on all platforms (the accessor -performs a swap operation on big endian machines), and also because -the layout of things is generally not known to the user. - -For structs, layout is deterministic and guaranteed to be the same -across platforms (scalars are aligned to their -own size, and structs themselves to their largest member), and you -are allowed to access this memory directly by using `safe_slice` -on the reference to a struct, or even an array of structs. - -To compute offsets to sub-elements of a struct, make sure they -are structs themselves, as then you can use the pointers to -figure out the offset without having to hardcode it. This is -handy for use of arrays of structs with calls like `glVertexAttribPointer` -in OpenGL or similar APIs. - -It is important to note is that structs are still little endian on all -machines, so the functions to enable tricks like this are only exposed on little -endian machines. If you also ship on big endian machines, using an -`#[cfg(target_endian = "little")]` attribute would be wise or your code will not -compile. - -The special function `safe_slice` is implemented on Vector objects that are -represented in memory the same way as they are represented on the wire. This -function is always available on vectors of struct, bool, u8, and i8. It is -conditionally-compiled on little-endian systems for all the remaining scalar -types. - -The FlatBufferBuilder function `create_vector_direct` is implemented for all -types that are endian-safe to write with a `memcpy`. It is the write-equivalent -of `safe_slice`. - -## Access of untrusted buffers - -The safe Rust functions to interpret a slice as a table (`root`, -`size_prefixed_root`, `root_with_opts`, and `size_prefixed_root_with_opts`) -verify the data first. This has some performance cost, but is intended to be -safe for use on flatbuffers from untrusted sources. There are corresponding -`unsafe` versions with names ending in `_unchecked` which skip this -verification, and may access arbitrary memory. - -The generated accessor functions access fields over offsets, which is -very quick. The current implementation uses these to access memory without any -further bounds checking. All of the safe Rust APIs ensure the verifier is run -over these flatbuffers before accessing them. - -When you're processing large amounts of data from a source you know (e.g. -your own generated data on disk), the `_unchecked` versions are acceptable, but -when reading data from the network that can potentially have been modified by an -attacker, it is desirable to use the safe versions which use the verifier. - -## Threading - -Reading a FlatBuffer does not touch any memory outside the original buffer, -and is entirely read-only (all immutable), so is safe to access from multiple -threads even without synchronisation primitives. - -Creating a FlatBuffer is not thread safe. All state related to building -a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory -outside of it is touched. To make this thread safe, either do not -share instances of FlatBufferBuilder between threads (recommended), or -manually wrap it in synchronisation primitives. There's no automatic way to -accomplish this, by design, as we feel multithreaded construction -of a single buffer will be rare, and synchronisation overhead would be costly. - -Unlike most other languages, in Rust these properties are exposed to and -enforced by the type system. `flatbuffers::Table` and the generated table types -are `Send + Sync`, indicating they may be freely shared across threads and data -may be accessed from any thread which receives a const (aka shared) reference. -There are no functions which require a mutable (aka exclusive) reference, which -means all the available functions may be called like this. -`flatbuffers::FlatBufferBuilder` is also `Send + Sync`, but all of the mutating -functions require a mutable (aka exclusive) reference which can only be created -when no other references to the `FlatBufferBuilder` exist, and may not be copied -within the same thread, let alone to a second thread. - -## Useful tools created by others - -* [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler -(flatc) as API for transparent `.fbs` to `.rs` code-generation via Cargo -build scripts integration. - -
diff --git a/docs-old/source/Schemas.md b/docs-old/source/Schemas.md deleted file mode 100644 index f049cf40b9d..00000000000 --- a/docs-old/source/Schemas.md +++ /dev/null @@ -1,685 +0,0 @@ -Writing a schema {#flatbuffers_guide_writing_schema} -================ - -The syntax of the schema language (aka IDL, [Interface Definition Language][]) -should look quite familiar to users of any of the C family of -languages, and also to users of other IDLs. Let's look at an example -first: - - // example IDL file - - namespace MyGame; - - attribute "priority"; - - enum Color : byte { Red = 1, Green, Blue } - - union Any { Monster, Weapon, Pickup } - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated, priority: 1); - inventory:[ubyte]; - color:Color = Blue; - test:Any; - } - - root_type Monster; - -(`Weapon` & `Pickup` not defined as part of this example). - -### Tables - -Tables are the main way of defining objects in FlatBuffers, and consist of a -name (here `Monster`) and a list of fields. Each field has a name, a type, and -optionally a default value. If the default value is not specified in the schema, -it will be `0` for scalar types, or `null` for other types. Some languages -support setting a scalar's default to `null`. This makes the scalar optional. - -Fields do not have to appear in the wire representation, and you can choose -to omit fields when constructing an object. You have the flexibility to add -fields without fear of bloating your data. This design is also FlatBuffer's -mechanism for forward and backwards compatibility. Note that: - -- You can add new fields in the schema ONLY at the end of a table - definition. Older data will still - read correctly, and give you the default value when read. Older code - will simply ignore the new field. - If you want to have flexibility to use any order for fields in your - schema, you can manually assign ids (much like Protocol Buffers), - see the `id` attribute below. - -- You cannot delete fields you don't use anymore from the schema, - but you can simply - stop writing them into your data for almost the same effect. - Additionally you can mark them as `deprecated` as in the example - above, which will prevent the generation of accessors in the - generated C++, as a way to enforce the field not being used any more. - (careful: this may break code!). - -- You may change field names and table names, if you're ok with your - code breaking until you've renamed them there too. - -See "Schema evolution examples" below for more on this -topic. - -### Structs - -Similar to a table, only now none of the fields are optional (so no defaults -either), and fields may not be added or be deprecated. Structs may only contain -scalars or other structs. Use this for -simple objects where you are very sure no changes will ever be made -(as quite clear in the example `Vec3`). Structs use less memory than -tables and are even faster to access (they are always stored in-line in their -parent object, and use no virtual table). - -### Types - -Built-in scalar types are - -- 8 bit: `byte` (`int8`), `ubyte` (`uint8`), `bool` - -- 16 bit: `short` (`int16`), `ushort` (`uint16`) - -- 32 bit: `int` (`int32`), `uint` (`uint32`), `float` (`float32`) - -- 64 bit: `long` (`int64`), `ulong` (`uint64`), `double` (`float64`) - -The type names in parentheses are alias names such that for example -`uint8` can be used in place of `ubyte`, and `int32` can be used in -place of `int` without affecting code generation. - -Built-in non-scalar types: - -- Vector of any other type (denoted with `[type]`). Nesting vectors - is not supported, instead you can wrap the inner vector in a table. - -- `string`, which may only hold UTF-8 or 7-bit ASCII. For other text encodings - or general binary data use vectors (`[byte]` or `[ubyte]`) instead. - -- References to other tables or structs, enums or unions (see - below). - -You can't change types of fields once they're used, with the exception -of same-size data where a `reinterpret_cast` would give you a desirable result, -e.g. you could change a `uint` to an `int` if no values in current data use the -high bit yet. - -### Arrays - -Arrays are a convenience short-hand for a fixed-length collection of elements. -Arrays can be used to replace the following schema: - - struct Vec3 { - x:float; - y:float; - z:float; - } - -with the following schema: - - struct Vec3 { - v:[float:3]; - } - -Both representations are binary equivalent. - -Arrays are currently only supported in a `struct`. - -### Default, Optional and Required Values - -There are three, mutually exclusive, reactions to the non-presence of a table's -field in the binary data: - -1. Default valued fields will return the default value (as defined in the schema). -2. Optional valued fields will return some form of `null` depending on the - local language. (In a sense, `null` is the default value). -3. Required fields will cause an error. Flatbuffer verifiers would - consider the whole buffer invalid. See the `required` tag below. - -When writing a schema, values are a sequence of digits. Values may be optionally -followed by a decimal point (`.`) and more digits, for float constants, or -optionally prefixed by a `-`. Floats may also be in scientific notation; -optionally ending with an `e` or `E`, followed by a `+` or `-` and more digits. -Values can also be the keyword `null`. - -Only scalar values can have defaults, non-scalar (string/vector/table) fields -default to `null` when not present. - -You generally do not want to change default values after they're initially -defined. Fields that have the default value are not actually stored in the -serialized data (see also Gotchas below). Values explicitly written by code -generated by the old schema old version, if they happen to be the default, will -be read as a different value by code generated with the new schema. This is -slightly less bad when converting an optional scalar into a default valued -scalar since non-presence would not be overloaded with a previous default value. -There are situations, however, where this may be desirable, especially if you -can ensure a simultaneous rebuild of all code. - -### Enums - -Define a sequence of named constants, each with a given value, or -increasing by one from the previous one. The default first value -is `0`. As you can see in the enum declaration, you specify the underlying -integral type of the enum with `:` (in this case `byte`), which then determines -the type of any fields declared with this enum type. - -Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`, -`uint`, `long` and `ulong`. - -Typically, enum values should only ever be added, never removed (there is no -deprecation for enums). This requires code to handle forwards compatibility -itself, by handling unknown enum values. - -### Unions - -Unions share a lot of properties with enums, but instead of new names -for constants, you use names of tables. You can then declare -a union field, which can hold a reference to any of those types, and -additionally a field with the suffix `_type` is generated that holds -the corresponding enum value, allowing you to know which type to cast -to at runtime. - -It's possible to give an alias name to a type union. This way a type can even be -used to mean different things depending on the name used: - - table PointPosition { x:uint; y:uint; } - table MarkerPosition {} - union Position { - Start:MarkerPosition, - Point:PointPosition, - Finish:MarkerPosition - } - -Unions contain a special `NONE` marker to denote that no value is stored so that -name cannot be used as an alias. - -Unions are a good way to be able to send multiple message types as a FlatBuffer. -Note that because a union field is really two fields, it must always be -part of a table, it cannot be the root of a FlatBuffer by itself. - -If you have a need to distinguish between different FlatBuffers in a more -open-ended way, for example for use as files, see the file identification -feature below. - -There is an experimental support only in C++ for a vector of unions (and -types). In the example IDL file above, use [Any] to add a vector of Any to -Monster table. There is also experimental support for other types besides -tables in unions, in particular structs and strings. There's no direct support -for scalars in unions, but they can be wrapped in a struct at no space cost. - -### Namespaces - -These will generate the corresponding namespace in C++ for all helper -code, and packages in Java. You can use `.` to specify nested namespaces / -packages. - -### Includes - -You can include other schemas files in your current one, e.g.: - - include "mydefinitions.fbs"; - -This makes it easier to refer to types defined elsewhere. `include` -automatically ensures each file is parsed just once, even when referred to -more than once. - -When using the `flatc` compiler to generate code for schema definitions, -only definitions in the current file will be generated, not those from the -included files (those you still generate separately). - -### Root type - -This declares what you consider to be the root table of the serialized -data. This is particularly important for parsing JSON data, which doesn't -include object type information. - -### File identification and extension - -Typically, a FlatBuffer binary buffer is not self-describing, i.e. it -needs you to know its schema to parse it correctly. But if you -want to use a FlatBuffer as a file format, it would be convenient -to be able to have a "magic number" in there, like most file formats -have, to be able to do a sanity check to see if you're reading the -kind of file you're expecting. - -Now, you can always prefix a FlatBuffer with your own file header, -but FlatBuffers has a built-in way to add an identifier to a -FlatBuffer that takes up minimal space, and keeps the buffer -compatible with buffers that don't have such an identifier. - -You can specify in a schema, similar to `root_type`, that you intend -for this type of FlatBuffer to be used as a file format: - - file_identifier "MYFI"; - -Identifiers must always be exactly 4 characters long. These 4 characters -will end up as bytes at offsets 4-7 (inclusive) in the buffer. - -For any schema that has such an identifier, `flatc` will automatically -add the identifier to any binaries it generates (with `-b`), -and generated calls like `FinishMonsterBuffer` also add the identifier. -If you have specified an identifier and wish to generate a buffer -without one, you can always still do so by calling -`FlatBufferBuilder::Finish` explicitly. - -After loading a buffer, you can use a call like -`MonsterBufferHasIdentifier` to check if the identifier is present. - -Note that this is best for open-ended uses such as files. If you simply wanted -to send one of a set of possible messages over a network for example, you'd -be better off with a union. - -Additionally, by default `flatc` will output binary files as `.bin`. -This declaration in the schema will change that to whatever you want: - - file_extension "ext"; - -### RPC interface declarations - -You can declare RPC calls in a schema, that define a set of functions -that take a FlatBuffer as an argument (the request) and return a FlatBuffer -as the response (both of which must be table types): - - rpc_service MonsterStorage { - Store(Monster):StoreResponse; - Retrieve(MonsterId):Monster; - } - -What code this produces and how it is used depends on language and RPC system -used, there is preliminary support for GRPC through the `--grpc` code generator, -see `grpc/tests` for an example. - -### Comments & documentation - -May be written as in most C-based languages. Additionally, a triple -comment (`///`) on a line by itself signals that a comment is documentation -for whatever is declared on the line after it -(table/struct/field/enum/union/element), and the comment is output -in the corresponding C++ code. Multiple such lines per item are allowed. - -### Attributes - -Attributes may be attached to a declaration, behind a field/enum value, -or after the name of a table/struct/enum/union. These may either have -a value or not. Some attributes like `deprecated` are understood by -the compiler; user defined ones need to be declared with the attribute -declaration (like `priority` in the example above), and are -available to query if you parse the schema at runtime. -This is useful if you write your own code generators/editors etc., and -you wish to add additional information specific to your tool (such as a -help text). - -Current understood attributes: - -- `id: n` (on a table field): manually set the field identifier to `n`. - If you use this attribute, you must use it on ALL fields of this table, - and the numbers must be a contiguous range from 0 onwards. - Additionally, since a union type effectively adds two fields, its - id must be that of the second field (the first field is the type - field and not explicitly declared in the schema). - For example, if the last field before the union field had id 6, - the union field should have id 8, and the unions type field will - implicitly be 7. - IDs allow the fields to be placed in any order in the schema. - When a new field is added to the schema it must use the next available ID. -- `deprecated` (on a field): do not generate accessors for this field - anymore, code should stop using this data. Old data may still contain this - field, but it won't be accessible anymore by newer code. Note that if you - deprecate a field that was previous required, old code may fail to validate - new data (when using the optional verifier). -- `required` (on a non-scalar table field): this field must always be set. - By default, fields do not need to be present in the binary. This is - desirable, as it helps with forwards/backwards compatibility, and - flexibility of data structures. By specifying this attribute, you make non- - presence in an error for both reader and writer. The reading code may access - the field directly, without checking for null. If the constructing code does - not initialize this field, they will get an assert, and also the verifier - will fail on buffers that have missing required fields. Both adding and - removing this attribute may be forwards/backwards incompatible as readers - will be unable read old or new data, respectively, unless the data happens to - always have the field set. -- `force_align: size` (on a struct): force the alignment of this struct - to be something higher than what it is naturally aligned to. Causes - these structs to be aligned to that amount inside a buffer, IF that - buffer is allocated with that alignment (which is not necessarily - the case for buffers accessed directly inside a `FlatBufferBuilder`). - Note: currently not guaranteed to have an effect when used with - `--object-api`, since that may allocate objects at alignments less than - what you specify with `force_align`. -- `force_align: size` (on a vector): force the alignment of this vector to be - something different than what the element size would normally dictate. - Note: Now only work for generated C++ code. -- `bit_flags` (on an unsigned enum): the values of this field indicate bits, - meaning that any unsigned value N specified in the schema will end up - representing 1< - -### Testing whether a field is present in a table - -Most serialization formats (e.g. JSON or Protocol Buffers) make it very -explicit in the format whether a field is present in an object or not, -allowing you to use this as "extra" information. - -FlatBuffers will not write fields that are equal to their default value, -sometimes resulting in significant space savings. However, this also means we -cannot disambiguate the meaning of non-presence as "written default value" or -"not written at all". This only applies to scalar fields since only they support -default values. Unless otherwise specified, their default is 0. - -If you care about the presence of scalars, most languages support "optional -scalars." You can set `null` as the default value in the schema. `null` is a -value that's outside of all types, so we will always write if `add_field` is -called. The generated field accessor should use the local language's canonical -optional type. - -Some `FlatBufferBuilder` implementations have an option called `force_defaults` -that circumvents this "not writing defaults" behavior you can then use -`IsFieldPresent` to query presence. -/ -Another option that works in all languages is to wrap a scalar field in a -struct. This way it will return null if it is not present. This will be slightly -less ergonomic but structs don't take up any more space than the scalar they -represent. - - [Interface Definition Language]: https://en.wikipedia.org/wiki/Interface_description_language - -## Writing your own code generator. - -See [our intermediate representation](@ref intermediate_representation). diff --git a/docs-old/source/Support.md b/docs-old/source/Support.md deleted file mode 100644 index 3436a6fbd11..00000000000 --- a/docs-old/source/Support.md +++ /dev/null @@ -1,57 +0,0 @@ -Platform / Language / Feature support {#flatbuffers_support} -===================================== - -FlatBuffers is actively being worked on, which means that certain platform / -language / feature combinations may not be available yet. - -This page tries to track those issues, to make informed decisions easier. -In general: - - * Languages: language support beyond the ones created by the original - FlatBuffer authors typically depends on community contributions. - * Features: C++ was the first language supported, since our original - target was high performance game development. It thus has the richest - feature set, and is likely most robust. Other languages are catching up - however. - * Platforms: All language implementations are typically portable to most - platforms, unless where noted otherwise. - -NOTE: this table is a start, it needs to be extended. - -Feature | C++ | Java | C# | Go | Python | JS | TS | C | PHP | Dart | Lobster | Rust | Swift ------------------------------- | ------ | ----- | -------- | ----- | ------ | ----- | --- | ------ | --- | ------- | ------- | ------ | ------ -Codegen for all basic features | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | WiP | Yes | Yes | Yes | Yes -JSON parsing | Yes | No | No | No | No | No | No | Yes | No | No | Yes | No | No -Simple mutation | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | No | Yes -Reflection | Yes | No | No | No | No | No | No | Basic | No | No | No | No | No -Buffer verifier | Yes | No | No | No | No | No | No | Yes | No | No | No | No | No -Native Object API | Yes | No | Yes | Yes | Yes | Yes | Yes | No | No | Yes | No | No | No -Optional Scalars | Yes | Yes | Yes | No | No | Yes | Yes | Yes | No | No | Yes | Yes | Yes -Flexbuffers | Yes | Yes | ? | ? | ? | ? | ? | ? | ? | ? | ? | Yes | ? -Testing: basic | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | ? | Yes | Yes | Yes | Yes -Testing: fuzz | Yes | No | No | Yes | Yes | No | No | No | ? | No | No | Yes | No -Performance: | Superb | Great | Great | Great | Ok | ? | ? | Superb | ? | ? | Great | Superb | Great -Platform: Windows | VS2010 | Yes | Yes | ? | ? | ? | Yes | VS2010 | ? | Yes | Yes | Yes | No -Platform: Linux | GCC282 | Yes | ? | Yes | Yes | ? | Yes | Yes | ? | Yes | Yes | Yes | Yes -Platform: OS X | Xcode4 | ? | ? | ? | Yes | ? | Yes | Yes | ? | Yes | Yes | Yes | Yes -Platform: Android | NDK10d | Yes | ? | ? | ? | ? | ? | ? | ? | Flutter | Yes | ? | No -Platform: iOS | ? | ? | ? | ? | ? | ? | ? | ? | ? | Flutter | Yes | ? | Yes -Engine: Unity | ? | ? | Yes | ? | ? | ? | ? | ? | ? | ? | No | ? | No -Primary authors (github) | aard | aard | ev/js/df | rw | rw | ew/ev | kr | mik | ch | df | aard | rw/cn | mi/mz - -Above | Github username ------ | ----------------------------- -aard | aardappel (previously: gwvo) -ch | chobie -cn | caspern -df | dnfield -ev | evolutional -ew | evanw -js | jonsimantov -kr | krojew -mi | mustiikhalil -mik | mikkelfj -mz | mzaks -rw | rw - -
diff --git a/docs-old/source/SwiftUsage.md b/docs-old/source/SwiftUsage.md deleted file mode 100644 index c6116f6ae99..00000000000 --- a/docs-old/source/SwiftUsage.md +++ /dev/null @@ -1,97 +0,0 @@ -Use in Swift {#flatbuffers_guide_use_swift} -========= - -## Before you get started - -Before diving into the FlatBuffers usage in Swift, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide -to general FlatBuffers usage in all of the supported languages (including Swift). -This page is designed to cover the nuances of FlatBuffers usage, specific to -Swift. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers Swift library code location - -The code for the FlatBuffers Swift library can be found at -`flatbuffers/swift`. You can browse the library code on the [FlatBuffers -GitHub page](https://github.com/google/flatbuffers/tree/master/swift). - -## Testing the FlatBuffers Swift library - -The code to test the Swift library can be found at `flatbuffers/tests/swift/tests`. -The test code itself is located in [flatbuffers/tests/swift/tests](https://github.com/google/flatbuffers/blob/master/tests/swift/tests). - -To run the tests, use the [SwiftTest.sh](https://github.com/google/flatbuffers/blob/master/tests/swift/tests/SwiftTest.sh) shell script. - -*Note: The shell script requires [Swift](https://swift.org) to -be installed.* - -## Using the FlatBuffers Swift library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in Swift.* - -FlatBuffers supports reading and writing binary FlatBuffers in Swift. - -To use FlatBuffers in your own code, first generate Swift structs from your -schema with the `--swift` option to `flatc`. Then include FlatBuffers using `SPM` in -by adding the path to `FlatBuffers/swift` into it. The generated code should also be -added to xcode or the path of the package you will be using. Note: sometimes xcode cant -and wont see the generated files, so it's better that you copy them to xcode. - -For example, here is how you would read a FlatBuffer binary file in Swift: First, -include the library and copy thegenerated code. Then read a FlatBuffer binary file or -a data object from the server, which you can pass into the `GetRootAsMonster` function. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} - import FlatBuffers - - typealias Monster1 = MyGame.Sample.Monster - typealias Vec3 = MyGame.Sample.Vec3 - - let path = FileManager.default.currentDirectoryPath - let url = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("monsterdata_test").appendingPathExtension("mon") - guard let data = try? Data(contentsOf: url) else { return } - - let monster = Monster.getRootAsMonster(bb: ByteBuffer(data: data)) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now you can access values like this: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} - let hp = monster.hp - let pos = monster.pos // uses native swift structs - let pos = monster.mutablePos // uses flatbuffers structs -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} - var byteBuffer = ByteBuffer(bytes: data) - // Get an accessor to the root object inside the buffer. - let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) - // let monster: Monster = getRoot(byteBuffer: &byteBuffer) - - if !monster.mutate(hp: 10) { - fatalError("couldn't mutate") - } - // mutate a struct field using flatbuffers struct - // DONT use monster.pos to mutate since swift copy on write - // will not mutate the value in the buffer - let vec = monster.mutablePos.mutate(z: 4) - - // This mutation will fail because the mana field is not available in - // the buffer. It should be set when creating the buffer. - if !monster.mutate(mana: 20) { - fatalError("couldn't mutate") - } -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The term `mutate` is used instead of `set` to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer. - -
diff --git a/docs-old/source/Tutorial.md b/docs-old/source/Tutorial.md deleted file mode 100644 index 70196fd29c9..00000000000 --- a/docs-old/source/Tutorial.md +++ /dev/null @@ -1,3563 +0,0 @@ -Tutorial {#flatbuffers_guide_tutorial} -======== - -## Overview - -This tutorial provides a basic example of how to work with -[FlatBuffers](@ref flatbuffers_overview). We will step through a simple example -application, which shows you how to: - - - Write a FlatBuffer `schema` file. - - Use the `flatc` FlatBuffer compiler. - - Parse [JSON](http://json.org) files that conform to a schema into - FlatBuffer binary files. - - Use the generated files in many of the supported languages (such as C++, - Java, and more.) - -During this example, imagine that you are creating a game where the main -character, the hero of the story, needs to slay some `orc`s. We will walk -through each step necessary to create this monster type using FlatBuffers. - -Please select your desired language for our quest: -\htmlonly -
- C++ - Java - Kotlin - C# - Go - Python - JavaScript - TypeScript - PHP - C - Dart - Lua - Lobster - Rust - Swift -
-\endhtmlonly - -\htmlonly - -\endhtmlonly - -## Where to Find the Example Code - -Samples demonstating the concepts in this example are located in the source code -package, under the `samples` directory. You can browse the samples on GitHub -[here](https://github.com/google/flatbuffers/tree/master/samples). - -
-*Note: The above does not apply to C, instead [look here](https://github.com/dvidelabs/flatcc/tree/master/samples).* -
- -For your chosen language, please cross-reference with: - -
-[sample_binary.cpp](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp) -
-
-[SampleBinary.java](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java) -
-
-[SampleBinary.kt](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.kt) -
-
-[SampleBinary.cs](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.cs) -
-
-[sample_binary.go](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.go) -
-
-[sample_binary.py](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py) -
-
-No sample binary is provided, since JS needs to be transpiled from TypeScript. Please see TypeScript support. -
-
-none yet -
-
-[SampleBinary.php](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.php) -
-
-[monster.c](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c) -
-
-[example.dart](https://github.com/google/flatbuffers/blob/master/dart/example/example.dart) -
-
-[sample_binary.lua](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lua) -
-
-[sample_binary.lobster](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.lobster) -
-
-[sample_binary.rs](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs) -
-
-[sample_binary.swift](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.swift) -
- - -## Writing the Monsters' FlatBuffer Schema - -To start working with FlatBuffers, you first need to create a `schema` file, -which defines the format for each data structure you wish to serialize. Here is -the `schema` that defines the template for our monsters: - -~~~ - // Example IDL file for our monster's schema. - - namespace MyGame.Sample; - - enum Color:byte { Red = 0, Green, Blue = 2 } - - union Equipment { Weapon } // Optionally add more tables. - - struct Vec3 { - x:float; - y:float; - z:float; - } - - table Monster { - pos:Vec3; // Struct. - mana:short = 150; - hp:short = 100; - name:string; - friendly:bool = false (deprecated); - inventory:[ubyte]; // Vector of scalars. - color:Color = Blue; // Enum. - weapons:[Weapon]; // Vector of tables. - equipped:Equipment; // Union. - path:[Vec3]; // Vector of structs. - } - - table Weapon { - name:string; - damage:short; - } - - root_type Monster; -~~~ - -As you can see, the syntax for the `schema` -[Interface Definition Language (IDL)](https://en.wikipedia.org/wiki/Interface_description_language) -is similar to those of the C family of languages, and other IDL languages. Let's -examine each part of this `schema` to determine what it does. - -The `schema` starts with a `namespace` declaration. This determines the -corresponding package/namespace for the generated code. In our example, we have -the `Sample` namespace inside of the `MyGame` namespace. - -Next, we have an `enum` definition. In this example, we have an `enum` of type -`byte`, named `Color`. We have three values in this `enum`: `Red`, `Green`, and -`Blue`. We specify `Red = 0` and `Blue = 2`, but we do not specify an explicit -value for `Green`. Since the behavior of an `enum` is to increment if -unspecified, `Green` will receive the implicit value of `1`. - -Following the `enum` is a `union`. The `union` in this example is not very -useful, as it only contains the one `table` (named `Weapon`). If we had created -multiple tables that we would want the `union` to be able to reference, we -could add more elements to the `union Equipment`. - -After the `union` comes a `struct Vec3`, which represents a floating point -vector with `3` dimensions. We use a `struct` here, over a `table`, because -`struct`s are ideal for data structures that will not change, since they use -less memory and have faster lookup. - -The `Monster` table is the main object in our FlatBuffer. This will be used as -the template to store our `orc` monster. We specify some default values for -fields, such as `mana:short = 150`. If unspecified, scalar fields (like `int`, -`uint`, or `float`) will be given a default of `0` while strings and tables will -be given a default of `null`. Another thing to note is the line `friendly:bool = -false (deprecated);`. Since you cannot delete fields from a `table` (to support -backwards compatibility), you can set fields as `deprecated`, which will prevent -the generation of accessors for this field in the generated code. Be careful -when using `deprecated`, however, as it may break legacy code that used this -accessor. - -The `Weapon` table is a sub-table used within our FlatBuffer. It is -used twice: once within the `Monster` table and once within the `Equipment` -union. For our `Monster`, it is used to populate a `vector of tables` via the -`weapons` field within our `Monster`. It is also the only table referenced by -the `Equipment` union. - -The last part of the `schema` is the `root_type`. The root type declares what -will be the root table for the serialized data. In our case, the root type is -our `Monster` table. - -The scalar types can also use alias type names such as `int16` instead -of `short` and `float32` instead of `float`. Thus we could also write -the `Weapon` table as: - -~~~ - table Weapon { - name:string; - damage:int16; - } -~~~ - -#### More Information About Schemas - -You can find a complete guide to writing `schema` files in the -[Writing a schema](@ref flatbuffers_guide_writing_schema) section of the -Programmer's Guide. You can also view the formal -[Grammar of the schema language](@ref flatbuffers_grammar). - -## Compiling the Monsters' Schema - -After you have written the FlatBuffers schema, the next step is to compile it. - -If you have not already done so, please follow -[these instructions](@ref flatbuffers_guide_building) to build `flatc`, the -FlatBuffer compiler. - -Once `flatc` is built successfully, compile the schema for your language: - -
-*Note: If you're working in C, you need to use the separate project [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema compiler and runtime library in C for C.* -
-See [flatcc build instructions](https://github.com/dvidelabs/flatcc#building). -
-Please be aware of the difference between `flatc` and `flatcc` tools. -
-
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --cpp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --java monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --kotlin monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --csharp monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --go monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --python monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --ts-flat-files --ts monster.fbs - # produces ts/js modules and js bundle monster_generated.js -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --ts monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/sample - ./../flatc --php monster.fbs -~~~ -
-
-~~~{.sh} - cd flatcc - mkdir -p build/tmp/samples/monster - bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs - # or just - flatcc/samples/monster/build.sh -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --dart monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lua monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --lobster monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --rust monster.fbs -~~~ -
-
-~~~{.sh} - cd flatbuffers/samples - ./../flatc --swift monster.fbs -~~~ -
- -For a more complete guide to using the `flatc` compiler, please read the -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) -section of the Programmer's Guide. - -## Reading and Writing Monster FlatBuffers - -Now that we have compiled the schema for our programming language, we can -start creating some monsters and serializing/deserializing them from -FlatBuffers. - -#### Creating and Writing Orc FlatBuffers - -The first step is to import/include the library, generated files, etc. - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kotlin} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using Google.FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Color - import MyGame.Sample.Equipment - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 - import MyGame.Sample.Weapon -~~~ -
-
-~~~{.js} - // The following code is an example - use your desired module flavor by transpiling from TS. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code is for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
-~~~{.ts} - // note: import flatbuffers with your desired import method - - import { MyGame } from './monster_generated'; -~~~ -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - #include "monster_builder.h" // Generated by `flatcc`. - - // Convenient namespace macro to manage long namespace prefix. - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. - - // A helper to simplify creating vectors from C-arrays. - #define c_vec_len(V) (sizeof(V)/sizeof((V)[0])) -~~~ -
-
-~~~{.dart} - import 'package:flat_buffers/flat_buffers.dart' as fb; - - // Generated by `flatc`. - import 'monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
-
-~~~{.swift} - /** - // make sure that monster_generated.swift is included in your project - */ - import Flatbuffers - - // typealiases for convenience - typealias Monster = MyGame1_Sample_Monster - typealias Weapon = MyGame1_Sample_Weapon - typealias Color = MyGame1_Sample_Color - typealias Vec3 = MyGame1_Sample_Vec3 -~~~ -
- -Now we are ready to start building some buffers. In order to start, we need -to create an instance of the `FlatBufferBuilder`, which will contain the buffer -as it grows. You can pass an initial size of the buffer (here 1024 bytes), -which will grow automatically if needed: - -
-~~~{.cpp} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - flatbuffers::FlatBufferBuilder builder(1024); -~~~ -
-
-~~~{.java} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - FlatBufferBuilder builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.kt} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - val builder = FlatBufferBuilder(1024) -~~~ -
-
-~~~{.cs} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new FlatBufferBuilder(1024); -~~~ -
-
-~~~{.go} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - builder := flatbuffers.NewBuilder(1024) -~~~ -
-
-~~~{.py} - # Create a `FlatBufferBuilder`, which will be used to create our - # monsters' FlatBuffers. - builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.js} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - var builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.ts} - // Create a `flatbuffer.Builder`, which will be used to create our - // monsters' FlatBuffers. - let builder = new flatbuffers.Builder(1024); -~~~ -
-
-~~~{.php} - // Create a `FlatBufferBuilder`, which will be used to create our - // monsters' FlatBuffers. - $builder = new Google\FlatBuffers\FlatbufferBuilder(1024); -~~~ -
-
-~~~{.c} - flatcc_builder_t builder, *B; - B = &builder; - // Initialize the builder object. - flatcc_builder_init(B); -~~~ -
-
-~~~{.dart} - // Create the fb.Builder object that will be used by our generated builders - // Note that if you are only planning to immediately get the byte array this builder would create, - // you can use the convenience method `toBytes()` on the generated builders. - // For example, you could do something like `new myGame.MonsterBuilder(...).toBytes()` - var builder = new fb.Builder(initialSize: 1024); -~~~ -
-
-~~~{.lua} - -- get access to the builder, providing an array of size 1024 - local builder = flatbuffers.Builder(1024) -~~~ -
-
-~~~{.lobster} - // get access to the builder - let builder = flatbuffers_builder {} -~~~ -
-
-~~~{.rs} - // Build up a serialized buffer algorithmically. - // Initialize it with a capacity of 1024 bytes. - let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024); -~~~ -
-
-~~~{.swift} - // create a `FlatBufferBuilder`, which will be used to serialize objects - let builder = FlatBufferBuilder(initialSize: 1024) -~~~ -
- -After creating the `builder`, we can start serializing our data. Before we make -our `orc` Monster, let's create some `Weapon`s: a `Sword` and an `Axe`. - -
-~~~{.cpp} - auto weapon_one_name = builder.CreateString("Sword"); - short weapon_one_damage = 3; - - auto weapon_two_name = builder.CreateString("Axe"); - short weapon_two_damage = 5; - - // Use the `CreateWeapon` shortcut to create Weapons with all the fields set. - auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); - auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); -~~~ -
-
-~~~{.java} - int weaponOneName = builder.createString("Sword") - short weaponOneDamage = 3; - - int weaponTwoName = builder.createString("Axe"); - short weaponTwoDamage = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - int sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); - int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); -~~~ -
-
-~~~{.kt} - val weaponOneName = builder.createString("Sword") - val weaponOneDamage: Short = 3; - - val weaponTwoName = builder.createString("Axe") - val weaponTwoDamage: Short = 5; - - // Use the `createWeapon()` helper function to create the weapons, since we set every field. - val sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage) - val axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage) -~~~ -
-
-~~~{.cs} - var weaponOneName = builder.CreateString("Sword"); - var weaponOneDamage = 3; - - var weaponTwoName = builder.CreateString("Axe"); - var weaponTwoDamage = 5; - - // Use the `CreateWeapon()` helper function to create the weapons, since we set every field. - var sword = Weapon.CreateWeapon(builder, weaponOneName, (short)weaponOneDamage); - var axe = Weapon.CreateWeapon(builder, weaponTwoName, (short)weaponTwoDamage); -~~~ -
-
-~~~{.go} - weaponOne := builder.CreateString("Sword") - weaponTwo := builder.CreateString("Axe") - - // Create the first `Weapon` ("Sword"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponOne) - sample.WeaponAddDamage(builder, 3) - sword := sample.WeaponEnd(builder) - - // Create the second `Weapon` ("Axe"). - sample.WeaponStart(builder) - sample.WeaponAddName(builder, weaponTwo) - sample.WeaponAddDamage(builder, 5) - axe := sample.WeaponEnd(builder) -~~~ -
-
-~~~{.py} - weapon_one = builder.CreateString('Sword') - weapon_two = builder.CreateString('Axe') - - # Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.Start(builder) - MyGame.Sample.Weapon.AddName(builder, weapon_one) - MyGame.Sample.Weapon.AddDamage(builder, 3) - sword = MyGame.Sample.Weapon.End(builder) - - # Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.Start(builder) - MyGame.Sample.Weapon.AddName(builder, weapon_two) - MyGame.Sample.Weapon.AddDamage(builder, 5) - axe = MyGame.Sample.Weapon.End(builder) -~~~ -
-
-~~~{.js} - var weaponOne = builder.createString('Sword'); - var weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - var sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - var axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.ts} - let weaponOne = builder.createString('Sword'); - let weaponTwo = builder.createString('Axe'); - - // Create the first `Weapon` ('Sword'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponOne); - MyGame.Sample.Weapon.addDamage(builder, 3); - let sword = MyGame.Sample.Weapon.endWeapon(builder); - - // Create the second `Weapon` ('Axe'). - MyGame.Sample.Weapon.startWeapon(builder); - MyGame.Sample.Weapon.addName(builder, weaponTwo); - MyGame.Sample.Weapon.addDamage(builder, 5); - let axe = MyGame.Sample.Weapon.endWeapon(builder); -~~~ -
-
-~~~{.php} - // Create the `Weapon`s using the `createWeapon()` helper function. - $weapon_one_name = $builder->createString("Sword"); - $sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one_name, 3); - - $weapon_two_name = $builder->createString("Axe"); - $axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two_name, 5); - - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - flatbuffers_string_ref_t weapon_one_name = flatbuffers_string_create_str(B, "Sword"); - uint16_t weapon_one_damage = 3; - - flatbuffers_string_ref_t weapon_two_name = flatbuffers_string_create_str(B, "Axe"); - uint16_t weapon_two_damage = 5; - - ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage)); - ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage)); -~~~ -
-
-~~~{.dart} - // The generated Builder classes work much like in other languages, - final int weaponOneName = builder.writeString("Sword"); - final int weaponOneDamage = 3; - - final int weaponTwoName = builder.writeString("Axe"); - final int weaponTwoDamage = 5; - - final swordBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponOneName) - ..addDamage(weaponOneDamage); - final int sword = swordBuilder.finish(); - - final axeBuilder = new myGame.WeaponBuilder(builder) - ..begin() - ..addNameOffset(weaponTwoName) - ..addDamage(weaponTwoDamage); - final int axe = axeBuilder.finish(); - - - - // The generated ObjectBuilder classes offer an easier to use alternative - // at the cost of requiring some additional reference allocations. If memory - // usage is critical, or if you'll be working with especially large messages - // or tables, you should prefer using the generated Builder classes. - // The following code would produce an identical buffer as above. - final String weaponOneName = "Sword"; - final int weaponOneDamage = 3; - - final String weaponTwoName = "Axe"; - final int weaponTwoDamage = 5; - - final myGame.WeaponBuilder sword = new myGame.WeaponObjectBuilder( - name: weaponOneName, - damage: weaponOneDamage, - ); - - final myGame.WeaponBuilder axe = new myGame.WeaponObjectBuilder( - name: weaponTwoName, - damage: weaponTwoDamage, - ); -~~~ -
-
-~~~{.lua} - local weaponOne = builder:CreateString("Sword") - local weaponTwo = builder:CreateString("Axe") - - -- Create the first 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponOne) - weapon.AddDamage(builder, 3) - local sword = weapon.End(builder) - - -- Create the second 'Weapon' - weapon.Start(builder) - weapon.AddName(builder, weaponTwo) - weapon.AddDamage(builder, 5) - local axe = weapon.End(builder) -~~~ -
-
-~~~{.lobster} - let weapon_names = [ "Sword", "Axe" ] - let weapon_damages = [ 3, 5 ] - - let weapon_offsets = map(weapon_names) name, i: - let ns = builder.CreateString(name) - MyGame_Sample_WeaponBuilder { b } - .start() - .add_name(ns) - .add_damage(weapon_damages[i]) - .end() -~~~ -
-
-~~~{.rs} - // Serialize some weapons for the Monster: A 'sword' and an 'axe'. - let weapon_one_name = builder.create_string("Sword"); - let weapon_two_name = builder.create_string("Axe"); - - // Use the `Weapon::create` shortcut to create Weapons with named field - // arguments. - let sword = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_one_name), - damage: 3, - }); - let axe = Weapon::create(&mut builder, &WeaponArgs{ - name: Some(weapon_two_name), - damage: 5, - }); -~~~ -
-
-~~~{.swift} - let weapon1Name = builder.create(string: "Sword") - let weapon2Name = builder.create(string: "Axe") - - // start creating the weapon by calling startWeapon - let weapon1Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon1Name, &builder) - Weapon.add(damage: 3, &builder) - // end the object by passing the start point for the weapon 1 - let sword = Weapon.endWeapon(&builder, start: weapon1Start) - - let weapon2Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon2Name, &builder) - Weapon.add(damage: 5, &builder) - let axe = Weapon.endWeapon(&builder, start: weapon2Start) -~~~ -
- -Now let's create our monster, the `orc`. For this `orc`, lets make him -`red` with rage, positioned at `(1.0, 2.0, 3.0)`, and give him -a large pool of hit points with `300`. We can give him a vector of weapons -to choose from (our `Sword` and `Axe` from earlier). In this case, we will -equip him with the `Axe`, since it is the most powerful of the two. Lastly, -let's fill his inventory with some potential treasures that can be taken once he -is defeated. - -Before we serialize a monster, we need to first serialize any objects that are -contained therein, i.e. we serialize the data tree using depth-first, pre-order -traversal. This is generally easy to do on any tree structures. - -
-~~~{.cpp} - // Serialize a name for our monster, called "Orc". - auto name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - unsigned char treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - auto inventory = builder.CreateVector(treasure, 10); -~~~ -
-
-~~~{.java} - // Serialize a name for our monster, called "Orc". - int name = builder.createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - int inv = Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.kt} - // Serialize a name for our monster, called "Orc". - val name = builder.createString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val inv = Monster.createInventoryVector(builder, treasure) -~~~ -
-
-~~~{.cs} - // Serialize a name for our monster, called "Orc". - var name = builder.CreateString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse order. - Monster.StartInventoryVector(builder, 10); - for (int i = 9; i >= 0; i--) - { - builder.AddByte((byte)i); - } - var inv = builder.EndVector(); -~~~ -
-
-~~~{.go} - // Serialize a name for our monster, called "Orc". - name := builder.CreateString("Orc") - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - // Note: Since we prepend the bytes, this loop iterates in reverse. - sample.MonsterStartInventoryVector(builder, 10) - for i := 9; i >= 0; i-- { - builder.PrependByte(byte(i)) - } - inv := builder.EndVector(10) -~~~ -
-
-~~~{.py} - # Serialize a name for our monster, called "Orc". - name = builder.CreateString("Orc") - - # Create a `vector` representing the inventory of the Orc. Each number - # could correspond to an item that can be claimed after he is slain. - # Note: Since we prepend the bytes, this loop iterates in reverse. - MyGame.Sample.Monster.StartInventoryVector(builder, 10) - for i in reversed(range(0, 10)): - builder.PrependByte(i) - inv = builder.EndVector() -~~~ -
-
-~~~{.js} - // Serialize a name for our monster, called 'Orc'. - var name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.ts} - // Serialize a name for our monster, called 'Orc'. - let name = builder.createString('Orc'); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - let treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); -~~~ -
-
-~~~{.php} - // Serialize a name for our monster, called "Orc". - $name = $builder->createString("Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); - $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure); -~~~ -
-
-~~~{.c} - // Serialize a name for our monster, called "Orc". - // The _str suffix indicates the source is an ascii-z string. - flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc"); - - // Create a `vector` representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - flatbuffers_uint8_vec_ref_t inventory; - // `c_vec_len` is the convenience macro we defined earlier. - inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure)); -~~~ -
-
-~~~{.dart} - // Serialize a name for our monster, called "Orc". - final int name = builder.writeString('Orc'); - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - final inventory = builder.writeListUint8(treasure); - - // The following code should be used instead if you intend to use the - // ObjectBuilder classes: - // Serialize a name for our monster, called "Orc". - final String name = 'Orc'; - - // Create a list representing the inventory of the Orc. Each number - // could correspond to an item that can be claimed after he is slain. - final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; -~~~ -
-
-~~~{.py} - -- Serialize a name for our monster, called 'orc' - local name = builder:CreateString("Orc") - - -- Create a `vector` representing the inventory of the Orc. Each number - -- could correspond to an item that can be claimed after he is slain. - -- Note: Since we prepend the bytes, this loop iterates in reverse. - monster.StartInventoryVector(builder, 10) - for i=10,1,-1 do - builder:PrependByte(i) - end - local inv = builder:EndVector(10) -~~~ -
-
-~~~{.lobster} - // Name of the monster. - let name = builder.CreateString("Orc") - - // Inventory. - let inv = builder.MyGame_Sample_MonsterCreateInventoryVector(map(10): _) -~~~ -
-
-~~~{.rs} - // Name of the Monster. - let name = builder.create_string("Orc"); - - // Inventory. - let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]); -~~~ -
-
-~~~{.swift} - // Name of the Monster. - let name = builder.create(string: "Orc") - - // create inventory - let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - let inventoryOffset = builder.createVector(inventory) -~~~ -
- -We serialized two built-in data types (`string` and `vector`) and captured -their return values. These values are offsets into the serialized data, -indicating where they are stored, such that we can refer to them below when -adding fields to our monster. - -*Note: To create a `vector` of nested objects (e.g. `table`s, `string`s, or -other `vector`s), collect their offsets into a temporary data structure, and -then create an additional `vector` containing their offsets.* - -If instead of creating a vector from an existing array you serialize elements -individually one by one, take care to note that this happens in reverse order, -as buffers are built back to front. - -For example, take a look at the two `Weapon`s that we created earlier (`Sword` -and `Axe`). These are both FlatBuffer `table`s, whose offsets we now store in -memory. Therefore we can create a FlatBuffer `vector` to contain these -offsets. - -
-~~~{.cpp} - // Place the weapons into a `std::vector`, then convert that into a FlatBuffer `vector`. - std::vector> weapons_vector; - weapons_vector.push_back(sword); - weapons_vector.push_back(axe); - auto weapons = builder.CreateVector(weapons_vector); -~~~ -
-
-~~~{.java} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - int[] weaps = new int[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - int weapons = Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.kt} - // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to - // create a FlatBuffer vector. - val weaps = intArrayOf(sword, axe) - - // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector. - val weapons = Monster.createWeaponsVector(builder, weaps) -~~~ -
-
-~~~{.cs} - var weaps = new Offset[2]; - weaps[0] = sword; - weaps[1] = axe; - - // Pass the `weaps` array into the `CreateWeaponsVector()` method to create a FlatBuffer vector. - var weapons = Monster.CreateWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.go} - // Create a FlatBuffer vector and prepend the weapons. - // Note: Since we prepend the data, prepend them in reverse order. - sample.MonsterStartWeaponsVector(builder, 2) - builder.PrependUOffsetT(axe) - builder.PrependUOffsetT(sword) - weapons := builder.EndVector(2) -~~~ -
-
-~~~{.py} - # Create a FlatBuffer vector and prepend the weapons. - # Note: Since we prepend the data, prepend them in reverse order. - MyGame.Sample.Monster.StartWeaponsVector(builder, 2) - builder.PrependUOffsetTRelative(axe) - builder.PrependUOffsetTRelative(sword) - weapons = builder.EndVector() -~~~ -
-
-~~~{.js} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - var weaps = [sword, axe]; - var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.ts} - // Create an array from the two `Weapon`s and pass it to the - // `createWeaponsVector()` method to create a FlatBuffer vector. - let weaps = [sword, axe]; - let weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); -~~~ -
-
-~~~{.php} - // Create an array from the two `Weapon`s and pass it to the - // `CreateWeaponsVector()` method to create a FlatBuffer vector. - $weaps = array($sword, $axe); - $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); -~~~ -
-
-~~~{.c} - // We use the internal builder stack to implement a dynamic vector. - ns(Weapon_vec_start(B)); - ns(Weapon_vec_push(B, sword)); - ns(Weapon_vec_push(B, axe)); - ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B)); -~~~ -
-
-~~~{.dart} - // If using the Builder classes, serialize the `[sword,axe]` - final weapons = builder.writeList([sword, axe]); - - // If using the ObjectBuilders, just create an array from the two `Weapon`s - final List weaps = [sword, axe]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the weapons. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartWeaponsVector(builder, 2) - builder:PrependUOffsetTRelative(axe) - builder:PrependUOffsetTRelative(sword) - local weapons = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - let weapons = builder.MyGame_Sample_MonsterCreateWeaponsVector(weapon_offsets) -~~~ -
-
-~~~{.rs} - // Create a FlatBuffer `vector` that contains offsets to the sword and axe - // we created above. - let weapons = builder.create_vector(&[sword, axe]); -~~~ -
-
-~~~{.swift} - // Create a FlatBuffer `vector` that contains offsets to the sword and axe - // we created above. - let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) -~~~ -
- -
-Note there are additional convenience overloads of `CreateVector`, allowing you -to work with data that's not in a `std::vector` or allowing you to generate -elements by calling a lambda. For the common case of `std::vector` -there's also `CreateVectorOfStrings`. -
- -Note that vectors of structs are serialized differently from tables, since -structs are stored in-line in the vector. For example, to create a vector -for the `path` field above: - -
-~~~{.cpp} - Vec3 points[] = { Vec3(1.0f, 2.0f, 3.0f), Vec3(4.0f, 5.0f, 6.0f) }; - auto path = builder.CreateVectorOfStructs(points, 2); -~~~ -
-
-~~~{.java} - Monster.startPathVector(fbb, 2); - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f); - int path = fbb.endVector(); -~~~ -
-
-~~~{.kt} - Monster.startPathVector(fbb, 2) - Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f) - Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f) - val path = fbb.endVector() -~~~ -
-
-~~~{.cs} - Monster.StartPathVector(fbb, 2); - Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f); - Vec3.CreateVec3(builder, 4.0f, 5.0f, 6.0f); - var path = fbb.EndVector(); -~~~ -
-
-~~~{.go} - sample.MonsterStartPathVector(builder, 2) - sample.CreateVec3(builder, 1.0, 2.0, 3.0) - sample.CreateVec3(builder, 4.0, 5.0, 6.0) - path := builder.EndVector(2) -~~~ -
-
-~~~{.py} - MyGame.Sample.Monster.StartPathVector(builder, 2) - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - MyGame.Sample.Vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - path = builder.EndVector() -~~~ -
-
-~~~{.js} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - var path = builder.endVector(); -~~~ -
-
-~~~{.ts} - MyGame.Sample.Monster.startPathVector(builder, 2); - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); - MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); - let path = builder.endVector(); -~~~ -
-
-~~~{.php} - \MyGame\Example\Monster::StartPathVector($builder, 2); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); - $path = $builder->endVector(); -~~~ -
-
-~~~{.c} - // TBD -~~~ -
-
-~~~{.dart} - // Using the Builder classes, you can write a list of structs like so: - // Note that the intended order should be reversed if order is important. - final vec3Builder = new myGame.Vec3Builder(builder); - vec3Builder.finish(4.0, 5.0, 6.0); - vec3Builder.finish(1.0, 2.0, 3.0); - final int path = builder.endStructVector(2); // the length of the vector - - // Otherwise, using the ObjectBuilder classes: - // The dart implementation provides a simple interface for writing vectors - // of structs, in `writeListOfStructs`. This method takes - // `List` and is used by the generated builder classes. - final List path = [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]; -~~~ -
-
-~~~{.lua} - -- Create a FlatBuffer vector and prepend the path locations. - -- Note: Since we prepend the data, prepend them in reverse order. - monster.StartPathVector(builder, 2) - vec3.CreateVec3(builder, 1.0, 2.0, 3.0) - vec3.CreateVec3(builder, 4.0, 5.0, 6.0) - local path = builder:EndVector(2) -~~~ -
-
-~~~{.lobster} - builder.MyGame_Sample_MonsterStartPathVector(2) - builder.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0) - builder.MyGame_Sample_CreateVec3(4.0, 5.0, 6.0) - let path = builder.EndVector(2) -~~~ -
-
-~~~{.rs} - // Create the path vector of Vec3 objects. - let x = Vec3::new(1.0, 2.0, 3.0); - let y = Vec3::new(4.0, 5.0, 6.0); - let path = builder.create_vector(&[x, y]); - - // Note that, for convenience, it is also valid to create a vector of - // references to structs, like this: - // let path = builder.create_vector(&[&x, &y]); -~~~ -
-
-~~~{.swift} - // - let points = fbb.createVector(ofStructs: [ - Vec3(x: 1, y: 2, z: 3), - Vec3(x: 4, y: 5, z: 6) - ]) - - // OR - var vec3 = [ - Vec3(x: 1, y: 2, z: 3), - Vec3(x: 4, y: 5, z: 6) - ] - Monster.startVectorOfVec3(2, in: &fbb) - for i in obj { - _ = create(struct: i) - } - let points = fbb.endVector(len: size) -~~~ -
- - -We have now serialized the non-scalar components of the orc, so we -can serialize the monster itself: - -
-~~~{.cpp} - // Create the position struct - auto position = Vec3(1.0f, 2.0f, 3.0f); - - // Set his hit points to 300 and his mana to 150. - int hp = 300; - int mana = 150; - - // Finally, create the monster using the `CreateMonster` helper function - // to set all fields. - auto orc = CreateMonster(builder, &position, mana, hp, name, inventory, - Color_Red, weapons, Equipment_Weapon, axe.Union(), - path); -~~~ -
-
-~~~{.java} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder); - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.addName(builder, name); - Monster.addColor(builder, Color.Red); - Monster.addHp(builder, (short)300); - Monster.addInventory(builder, inv); - Monster.addWeapons(builder, weapons); - Monster.addEquippedType(builder, Equipment.Weapon); - Monster.addEquipped(builder, axe); - Monster.addPath(builder, path); - int orc = Monster.endMonster(builder); -~~~ -
-
-~~~{.kt} - // Create our monster using `startMonster()` and `endMonster()`. - Monster.startMonster(builder) - Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)) - Monster.addName(builder, name) - Monster.addColor(builder, Color.Red) - Monster.addHp(builder, 300.toShort()) - Monster.addInventory(builder, inv) - Monster.addWeapons(builder, weapons) - Monster.addEquippedType(builder, Equipment.Weapon) - Monster.addEquipped(builder, axe) - Monster.addPath(builder, path) - val orc = Monster.endMonster(builder) -~~~ -
-
-~~~{.cs} - // Create our monster using `StartMonster()` and `EndMonster()`. - Monster.StartMonster(builder); - Monster.AddPos(builder, Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f)); - Monster.AddHp(builder, (short)300); - Monster.AddName(builder, name); - Monster.AddInventory(builder, inv); - Monster.AddColor(builder, Color.Red); - Monster.AddWeapons(builder, weapons); - Monster.AddEquippedType(builder, Equipment.Weapon); - Monster.AddEquipped(builder, axe.Value); // Axe - Monster.AddPath(builder, path); - var orc = Monster.EndMonster(builder); -~~~ -
-
-~~~{.go} - // Create our monster using `MonsterStart()` and `MonsterEnd()`. - sample.MonsterStart(builder) - sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0)) - sample.MonsterAddHp(builder, 300) - sample.MonsterAddName(builder, name) - sample.MonsterAddInventory(builder, inv) - sample.MonsterAddColor(builder, sample.ColorRed) - sample.MonsterAddWeapons(builder, weapons) - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) - sample.MonsterAddEquipped(builder, axe) - sample.MonsterAddPath(builder, path) - orc := sample.MonsterEnd(builder) -~~~ -
-
-~~~{.py} - # Create our monster by using `Monster.Start()` and `Monster.End()`. - MyGame.Sample.Monster.Start(builder) - MyGame.Sample.Monster.AddPos(builder, - MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - MyGame.Sample.Monster.AddHp(builder, 300) - MyGame.Sample.Monster.AddName(builder, name) - MyGame.Sample.Monster.AddInventory(builder, inv) - MyGame.Sample.Monster.AddColor(builder, - MyGame.Sample.Color.Color().Red) - MyGame.Sample.Monster.AddWeapons(builder, weapons) - MyGame.Sample.Monster.AddEquippedType( - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.AddEquipped(builder, axe) - MyGame.Sample.Monster.AddPath(builder, path) - orc = MyGame.Sample.Monster.End(builder) -~~~ -
-
-~~~{.js} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - var orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.ts} - // Create our monster by using `startMonster()` and `endMonster()`. - MyGame.Sample.Monster.startMonster(builder); - MyGame.Sample.Monster.addPos(builder, - MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); - MyGame.Sample.Monster.addHp(builder, 300); - MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) - MyGame.Sample.Monster.addName(builder, name); - MyGame.Sample.Monster.addInventory(builder, inv); - MyGame.Sample.Monster.addWeapons(builder, weapons); - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); - MyGame.Sample.Monster.addEquipped(builder, axe); - MyGame.Sample.Monster.addPath(builder, path); - let orc = MyGame.Sample.Monster.endMonster(builder); -~~~ -
-
-~~~{.php} - // Create our monster by using `StartMonster()` and `EndMonster()`. - \MyGame\Sample\Monster::StartMonster($builder); - \MyGame\Sample\Monster::AddPos($builder, - \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0)); - \MyGame\Sample\Monster::AddHp($builder, 300); - \MyGame\Sample\Monster::AddName($builder, $name); - \MyGame\Sample\Monster::AddInventory($builder, $inv); - \MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red); - \MyGame\Sample\Monster::AddWeapons($builder, $weapons); - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); - \MyGame\Sample\Monster::AddEquipped($builder, $axe); - \MyGame\Sample\Monster::AddPath($builder, $path); - $orc = \MyGame\Sample\Monster::EndMonster($builder); -~~~ -
-
-~~~{.c} - // Set his hit points to 300 and his mana to 150. - uint16_t hp = 300; - uint16_t mana = 150; - - // Define an equipment union. `create` calls in C has a single - // argument for unions where C++ has both a type and a data argument. - ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); - ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f }; - ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red), - weapons, equipped, path)); -~~~ -
-
-~~~{.dart} - // Using the Builder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - final monster = new myGame.MonsterBuilder(builder) - ..begin() - ..addNameOffset(name) - ..addInventoryOffset(inventory) - ..addWeaponsOffset(weapons) - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - ..addHp(hp) - ..addMana(mana) - ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) - ..addPathOffset(path) - ..addColor(myGame.Color.Red); - - final int orc = monster.finish(); - - // -Or- using the ObjectBuilder API: - // Set his hit points to 300 and his mana to 150. - final int hp = 300; - final int mana = 150; - - // Note that these parameters are optional - it is not necessary to set - // all of them. - // Also note that it is not necessary to `finish` the builder helpers above - // - the generated code will automatically reuse offsets if the same object - // is used in more than one place (e.g. the axe appearing in `weapons` and - // `equipped`). - final myGame.MonsterBuilder orcBuilder = new myGame.MonsterBuilder( - name: name, - inventory: treasure, - weapons: weaps, - equippedType: myGame.EquipmentTypeId.Weapon, - equipped: axe, - path: path, - hp: hp, - mana: mana, - pos: new myGame.Vec3Builder(x: 1.0, y: 2.0, z: 3.0), - color: myGame.Color.Red, - path: [ - new myGame.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), - new myGame.Vec3ObjectBuilder(x: 4.0, y: 5.0, z: 6.0) - ]); - - final int orc = orcBuilder.finish(builder); -~~~ -
-
-~~~{.lua} - -- Create our monster by using Start() andEnd() - monster.Start(builder) - monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) - monster.AddHp(builder, 300) - monster.AddName(builder, name) - monster.AddInventory(builder, inv) - monster.AddColor(builder, color.Red) - monster.AddWeapons(builder, weapons) - monster.AddEquippedType(builder, equipment.Weapon) - monster.AddEquipped(builder, axe) - monster.AddPath(builder, path) - local orc = monster.End(builder) -~~~ -
-
-~~~{.lobster} - let orc = MyGame_Sample_MonsterBuilder { b } - .start() - .add_pos(b.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0)) - .add_hp(300) - .add_name(name) - .add_inventory(inv) - .add_color(MyGame_Sample_Color_Red) - .add_weapons(weapons) - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(weapon_offsets[1]) - .add_path(path) - .end() -~~~ -
-
-~~~{.rs} - // Create the monster using the `Monster::create` helper function. This - // function accepts a `MonsterArgs` struct, which supplies all of the data - // needed to build a `Monster`. To supply empty/default fields, just use the - // Rust built-in `Default::default()` function, as demonstrated below. - let orc = Monster::create(&mut builder, &MonsterArgs{ - pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)), - mana: 150, - hp: 80, - name: Some(name), - inventory: Some(inventory), - color: Color::Red, - weapons: Some(weapons), - equipped_type: Equipment::Weapon, - equipped: Some(axe.as_union_value()), - path: Some(path), - ..Default::default() - }); -~~~ -
-
-~~~{.swift} - let orc = Monster.createMonster( - &builder, - pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3), - hp: 300, - nameOffset: name, - inventoryVectorOffset: inventoryOffset, - color: .red, - weaponsVectorOffset: weaponsOffset, - equippedType: .weapon, - equippedOffset: axe) -~~~ -
- -Note how we create `Vec3` struct in-line in the table. Unlike tables, structs -are simple combinations of scalars that are always stored inline, just like -scalars themselves. - -**Important**: Unlike structs, you should not nest tables or other objects, -which is why we created all the strings/vectors/tables that this monster refers -to before `start`. If you try to create any of them between `start` and `end`, -you will get an assert/exception/panic depending on your language. - -*Note: Since we are passing `150` as the `mana` field, which happens to be the -default value, the field will not actually be written to the buffer, since the -default value will be returned on query anyway. This is a nice space savings, -especially if default values are common in your data. It also means that you do -not need to be worried about adding a lot of fields that are only used in a small -number of instances, as it will not bloat the buffer if unused.* - -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `CreateMonster()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.cpp} - // You can use this code instead of `CreateMonster()`, to create our orc - // manually. - MonsterBuilder monster_builder(builder); - monster_builder.add_pos(&position); - monster_builder.add_hp(hp); - monster_builder.add_name(name); - monster_builder.add_inventory(inventory); - monster_builder.add_color(Color_Red); - monster_builder.add_weapons(weapons); - monster_builder.add_equipped_type(Equipment_Weapon); - monster_builder.add_equipped(axe.Union()); - auto orc = monster_builder.Finish(); -~~~ -
-
-If you do not wish to set every field in a `table`, it may be more convenient to -manually set each field of your monster, instead of calling `create_monster_as_root()`. -The following snippet is functionally equivalent to the above code, but provides -a bit more flexibility. -
-~~~{.c} - // It is important to pair `start_as_root` with `end_as_root`. - ns(Monster_start_as_root(B)); - ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f)); - // or alternatively - //ns(Monster_pos_add(&pos); - - ns(Monster_hp_add(B, hp)); - // Notice that `Monser_name_add` adds a string reference unlike the - // add_str and add_strn variants. - ns(Monster_name_add(B, name)); - ns(Monster_inventory_add(B, inventory)); - ns(Monster_color_add(B, ns(Color_Red))); - ns(Monster_weapons_add(B, weapons)); - ns(Monster_equipped_add(B, equipped)); - // Complete the monster object and make it the buffer root object. - ns(Monster_end_as_root(B)); -~~~ -
- -
-~~~{.swift} - let start = Monster.startMonster(&builder) - Monster.add(pos: Vec3(x: 1, y: 2, z: 3), &builder) - Monster.add(hp: 300, &builder) - Monster.add(name: name, &builder) - Monster.addVectorOf(inventory: inventoryOffset, &builder) - Monster.add(color: .red, &builder) - Monster.addVectorOf(weapons: weaponsOffset, &builder) - Monster.add(equippedType: .weapon, &builder) - Monster.add(equipped: axe, &builder) - var orc = Monster.endMonster(&builder, start: start) -~~~ -
- -Before finishing the serialization, let's take a quick look at FlatBuffer -`union Equipped`. There are two parts to each FlatBuffer `union`. The first is -a hidden field `_type` that is generated to hold the type of `table` referred -to by the `union`. This allows you to know which type to cast to at runtime. -Second is the `union`'s data. - -In our example, the last two things we added to our `Monster` were the -`Equipped Type` and the `Equipped` union itself. - -Here is a repetition of these lines, to help highlight them more clearly: - -
- ~~~{.cpp} - monster_builder.add_equipped_type(Equipment_Weapon); // Union type - monster_builder.add_equipped(axe.Union()); // Union data - ~~~ -
-
- ~~~{.java} - Monster.addEquippedType(builder, Equipment.Weapon); // Union type - Monster.addEquipped(axe); // Union data - ~~~ -
-
- ~~~{.kt} - Monster.addEquippedType(builder, Equipment.Weapon) // Union type - Monster.addEquipped(axe) // Union data - ~~~ -
-
- ~~~{.cs} - Monster.AddEquippedType(builder, Equipment.Weapon); // Union type - Monster.AddEquipped(builder, axe.Value); // Union data - ~~~ -
-
- ~~~{.go} - sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) // Union type - sample.MonsterAddEquipped(builder, axe) // Union data - ~~~ -
-
- ~~~{.py} - MyGame.Sample.Monster.AddEquippedType( # Union type - builder, MyGame.Sample.Equipment.Equipment().Weapon) - MyGame.Sample.Monster.AddEquipped(builder, axe) # Union data - ~~~ -
-
- ~~~{.js} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.ts} - MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type - MyGame.Sample.Monster.addEquipped(builder, axe); // Union data - ~~~ -
-
- ~~~{.php} - \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); // Union type - \MyGame\Sample\Monster::AddEquipped($builder, $axe); // Union data - ~~~ -
-
-~~~{.c} - // Add union type and data simultaneously. - ns(Monster_equipped_Weapon_add(B, axe)); -~~~ -
-
-~~~{.dart} - // using the builder API: - ..addEquippedType(myGame.EquipmentTypeId.Weapon) - ..addEquippedOffset(axe) - - // in the ObjectBuilder API: - equippedTypeId: myGame.EquipmentTypeId.Weapon, // Union type - equipped: axe, // Union data -~~~ -
-
-~~~{.lua} - monster.AddEquippedType(builder, equipment.Weapon) -- Union type - monster.AddEquipped(builder, axe) -- Union data -~~~ -
-
-~~~{.lobster} - .add_equipped_type(MyGame_Sample_Equipment_Weapon) - .add_equipped(axe) -~~~ -
-
- ~~~{.rs} - // You need to call `as_union_value` to turn an object into a type that - // can be used as a union value. - monster_builder.add_equipped_type(Equipment::Weapon); // Union type - monster_builder.add_equipped(axe.as_union_value()); // Union data - ~~~ -
-
- ~~~{.swift} - Monster.add(equippedType: .weapon, builder) // Type of union - Monster.add(equipped: axe, builder) // Union data - ~~~ -
- - -After you have created your buffer, you will have the offset to the root of the -data in the `orc` variable, so you can finish the buffer by calling the -appropriate `finish` method. - - -
-~~~{.cpp} - // Call `Finish()` to instruct the builder that this monster is complete. - // Note: Regardless of how you created the `orc`, you still need to call - // `Finish()` on the `FlatBufferBuilder`. - builder.Finish(orc); // You could also call `FinishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.java} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.kt} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc) // You could also call `Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.cs} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.go} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.py} - # Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.js} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.ts} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc); // You could also call `MyGame.Sample.Monster.finishMonsterBuffer(builder, orc);`. -~~~ -
-
-~~~{.php} - // Call `finish()` to instruct the builder that this monster is complete. - $builder->finish($orc); // You may also call `\MyGame\Sample\Monster::FinishMonsterBuffer($builder, $orc);`. -~~~ -
-
-~~~{.c} - // Because we used `Monster_create_as_root`, we do not need a `finish` call in C`. -~~~ -
-
-~~~{.dart} - // Call `finish()` to instruct the builder that this monster is complete. - // See the next code section, as in Dart `finish` will also return the byte array. -~~~ -
-
-~~~{.lua} - -- Call 'Finish()' to instruct the builder that this monster is complete. - builder:Finish(orc) -~~~ -
-
-~~~{.lobster} - // Call `Finish()` to instruct the builder that this monster is complete. - builder.Finish(orc) -~~~ -
-
-~~~{.rs} - // Call `finish()` to instruct the builder that this monster is complete. - builder.finish(orc, None); -~~~ -
-
-~~~{.swift} - // Call `finish(offset:)` to instruct the builder that this monster is complete. - builder.finish(offset: orc) -~~~ -
- -The buffer is now ready to be stored somewhere, sent over the network, be -compressed, or whatever you'd like to do with it. You can access the buffer -like so: - -
-~~~{.cpp} - // This must be called after `Finish()`. - uint8_t *buf = builder.GetBufferPointer(); - int size = builder.GetSize(); // Returns the size of the buffer that - // `GetBufferPointer()` points to. -~~~ -
-
-~~~{.java} - // This must be called after `finish()`. - java.nio.ByteBuffer buf = builder.dataBuffer(); - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.sizedByteArray(); -~~~ -
-
-~~~{.kt} - // This must be called after `finish()`. - val buf = builder.dataBuffer() - // The data in this ByteBuffer does NOT start at 0, but at buf.position(). - // The number of bytes is buf.remaining(). - - // Alternatively this copies the above data out of the ByteBuffer for you: - val buf = builder.sizedByteArray() -~~~ -
-
-~~~{.cs} - // This must be called after `Finish()`. - var buf = builder.DataBuffer; // Of type `FlatBuffers.ByteBuffer`. - // The data in this ByteBuffer does NOT start at 0, but at buf.Position. - // The end of the data is marked by buf.Length, so the size is - // buf.Length - buf.Position. - - // Alternatively this copies the above data out of the ByteBuffer for you: - byte[] buf = builder.SizedByteArray(); -~~~ -
-
-~~~{.go} - // This must be called after `Finish()`. - buf := builder.FinishedBytes() // Of type `byte[]`. -~~~ -
-
-~~~{.py} - # This must be called after `Finish()`. - buf = builder.Output() // Of type `bytearray`. -~~~ -
-
-~~~{.js} - // This must be called after `finish()`. - var buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.ts} - // This must be called after `finish()`. - let buf = builder.asUint8Array(); // Of type `Uint8Array`. -~~~ -
-
-~~~{.php} - // This must be called after `finish()`. - $buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer` - // The data in this ByteBuffer does NOT start at 0, but at buf->getPosition(). - // The end of the data is marked by buf->capacity(), so the size is - // buf->capacity() - buf->getPosition(). -~~~ -
-
-~~~{.c} - uint8_t *buf; - size_t size; - - // Allocate and extract a readable buffer from internal builder heap. - // The returned buffer must be deallocated using `free`. - // NOTE: Finalizing the buffer does NOT change the builder, it - // just creates a snapshot of the builder content. - buf = flatcc_builder_finalize_buffer(B, &size); - // use buf - free(buf); - - // Optionally reset builder to reuse builder without deallocating - // internal stack and heap. - flatcc_builder_reset(B); - // build next buffer. - // ... - - // Cleanup. - flatcc_builder_clear(B); -~~~ -
-
-~~~{.dart} - final Uint8List buf = builder.finish(orc); -~~~ -
-
-~~~{.lua} - -- Get the flatbuffer as a string containing the binary data - local bufAsString = builder:Output() -~~~ -
-
-~~~{.lobster} - // This must be called after `Finish()`. - let buf = builder.SizedCopy() // Of type `string`. -~~~ -
-
-~~~{.rs} - // This must be called after `finish()`. - // `finished_data` returns a byte slice. - let buf = builder.finished_data(); // Of type `&[u8]` -~~~ -
-
-~~~{.swift} - // This must be called after `finish()`. - // `sizedByteArray` returns the finished buf of type [UInt8]. - let buf = builder.sizedByteArray - // or you can use to get an object of type Data - let bufData = ByteBuffer(data: builder.data) -~~~ -
- -Now you can write the bytes to a file or send them over the network. -**Make sure your file mode (or transfer protocol) is set to BINARY, not text.** -If you transfer a FlatBuffer in text mode, the buffer will be corrupted, -which will lead to hard to find problems when you read the buffer. - -
-For example, in Node you can simply do: -~~~{.js} - writeFileSync('monster.bin', buf, 'binary'); -~~~ -
-
-For example, in Node you can simply do: -~~~{.ts} - writeFileSync('monster.bin', buf, 'binary'); -~~~ -
- -#### Reading Orc FlatBuffers - -Now that we have successfully created an `Orc` FlatBuffer, the monster data can -be saved, sent over a network, etc. Let's now adventure into the inverse, and -access a FlatBuffer. - -This section requires the same import/include, namespace, etc. requirements as -before: - -
-~~~{.cpp} - #include "monster_generated.h" // This was generated by `flatc`. - - using namespace MyGame::Sample; // Specified in the schema. -~~~ -
-
-~~~{.java} - import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder; -~~~ -
-
-~~~{.kt} - import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) - - import com.google.flatbuffers.FlatBufferBuilder -~~~ -
-
-~~~{.cs} - using Google.FlatBuffers; - using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.) -~~~ -
-
-~~~{.go} - import ( - flatbuffers "github.com/google/flatbuffers/go" - sample "MyGame/Sample" - ) -~~~ -
-
-~~~{.py} - import flatbuffers - - # Generated by `flatc`. - import MyGame.Sample.Any - import MyGame.Sample.Color - import MyGame.Sample.Monster - import MyGame.Sample.Vec3 -~~~ -
-
-~~~{.js} - // The following code is an example - use your desired module flavor by transpiling from TS. - var flatbuffers = require('/js/flatbuffers').flatbuffers; - var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. - - //--------------------------------------------------------------------------// - - // The following code an example for browser-based HTML/JavaScript. Use the above code - // for JavaScript module loaders (e.g. Node.js). - - // Generated by `flatc`. -~~~ -
-
-~~~{.ts} - // note: import flatbuffers with your desired import method - - // note: the `./monster_generated.js` file was previously generated by `flatc` above using the `monster.fbs` schema - import { MyGame } from './monster_generated'; -~~~ -
-
-~~~{.php} - // It is recommended that your use PSR autoload when using FlatBuffers in PHP. - // Here is an example from `SampleBinary.php`: - function __autoload($class_name) { - // The last segment of the class name matches the file name. - $class = substr($class_name, strrpos($class_name, "\\") + 1); - $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. - - // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. - $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), - join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample"))); - foreach ($paths as $path) { - $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); - if (file_exists($file)) { - require($file); - break; - } - } - } -~~~ -
-
-~~~{.c} - // Only needed if we don't have `#include "monster_builder.h"`. - #include "monster_reader.h" - - #undef ns - #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema. -~~~ -
-
-~~~{.dart} -import 'package:flat_buffers/flat_buffers.dart' as fb; -import './monster_my_game.sample_generated.dart' as myGame; -~~~ -
-
-~~~{.lua} - -- require the flatbuffers module - local flatbuffers = require("flatbuffers") - - -- require the generated files from `flatc`. - local color = require("MyGame.Sample.Color") - local equipment = require("MyGame.Sample.Equipment") - local monster = require("MyGame.Sample.Monster") - local vec3 = require("MyGame.Sample.Vec3") - local weapon = require("MyGame.Sample.Weapon") -~~~ -
-
-~~~{.lobster} - import from "../lobster/" // Where to find flatbuffers.lobster - import monster_generated -~~~ -
-
-~~~{.rs} - // import the flatbuffers runtime library - extern crate flatbuffers; - - // import the generated code - #[allow(dead_code, unused_imports)] - #[path = "./monster_generated.rs"] - mod monster_generated; - pub use monster_generated::my_game::sample::{root_as_monster, - Color, Equipment, - Monster, MonsterArgs, - Vec3, - Weapon, WeaponArgs}; -~~~ -
- -Then, assuming you have a buffer of bytes received from disk, -network, etc., you can start accessing the buffer like so: - -**Again, make sure you read the bytes in BINARY mode, otherwise the code below -won't work.** - -
-~~~{.cpp} - uint8_t *buffer_pointer = /* the data you just read */; - - // Get a pointer to the root object inside the buffer. - auto monster = GetMonster(buffer_pointer); - - // `monster` is of type `Monster *`. - // Note: root object pointers are NOT the same as `buffer_pointer`. - // `GetMonster` is a convenience function that calls `GetRoot`, - // the latter is also available for non-root types. -~~~ -
-
-~~~{.java} - byte[] bytes = /* the data you just read */ - java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes); - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.kt} - val bytes = /* the data you just read */ - val buf = java.nio.ByteBuffer.wrap(bytes) - - // Get an accessor to the root object inside the buffer. - Monster monster = Monster.getRootAsMonster(buf) -~~~ -
-
-~~~{.cs} - byte[] bytes = /* the data you just read */ - var buf = new ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = Monster.GetRootAsMonster(buf); -~~~ -
-
-~~~{.go} - var buf []byte = /* the data you just read */ - - // Get an accessor to the root object inside the buffer. - monster := sample.GetRootAsMonster(buf, 0) - - // Note: We use `0` for the offset here, which is typical for most buffers - // you would read. If you wanted to read from `builder.Bytes` directly, you - // would need to pass in the offset of `builder.Head()`, as the builder - // constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.py} - buf = /* the data you just read, in an object of type "bytearray" */ - - // Get an accessor to the root object inside the buffer. - monster = MyGame.Sample.Monster.Monster.GetRootAs(buf, 0) - - # Note: We use `0` for the offset here, which is typical for most buffers - # you would read. If you wanted to read from the `builder.Bytes` directly, - # you would need to pass in the offset of `builder.Head()`, as the builder - # constructs the buffer backwards, so may not start at offset 0. -~~~ -
-
-~~~{.js} - // the data you just read, as a `Uint8Array` - // Note that the example here uses `readFileSync` from the built-in `fs` module, - // but other methods for accessing the file contents will also work. - var bytes = new Uint8Array(readFileSync('./monsterdata.bin')); - - var buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - var monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.ts} - // the data you just read, as a `Uint8Array`. - // Note that the example here uses `readFileSync` from the built-in `fs` module, - // but other methods for accessing the file contents will also work. - let bytes = new Uint8Array(readFileSync('./monsterdata.bin')); - - let buf = new flatbuffers.ByteBuffer(bytes); - - // Get an accessor to the root object inside the buffer. - let monster = MyGame.Sample.Monster.getRootAsMonster(buf); -~~~ -
-
-~~~{.php} - $bytes = /* the data you just read, in a string */ - $buf = Google\FlatBuffers\ByteBuffer::wrap($bytes); - - // Get an accessor to the root object inside the buffer. - $monster = \MyGame\Sample\Monster::GetRootAsMonster($buf); -~~~ -
-
-~~~{.c} - // Note that we use the `table_t` suffix when reading a table object - // as opposed to the `ref_t` suffix used during the construction of - // the buffer. - ns(Monster_table_t) monster = ns(Monster_as_root(buffer)); - - // Note: root object pointers are NOT the same as the `buffer` pointer. -~~~ -
-
-~~~{.dart} -List data = ... // the data, e.g. from file or network -// A generated factory constructor that will read the data. -myGame.Monster monster = new myGame.Monster(data); -~~~ -
-
-~~~{.lua} - local bufAsString = -- The data you just read in - - -- Convert the string representation into binary array Lua structure - local buf = flatbuffers.binaryArray.New(bufAsString) - - -- Get an accessor to the root object insert the buffer - local mon = monster.GetRootAsMonster(buf, 0) -~~~ -
-
-~~~{.lobster} - buf = /* the data you just read, in a string */ - - // Get an accessor to the root object inside the buffer. - let monster = MyGame_Sample_GetRootAsMonster(buf) -~~~ -
-
-~~~{.rs} - let buf = /* the data you just read, in a &[u8] */ - - // Get an accessor to the root object inside the buffer. - let monster = root_as_monster(buf).unwrap(); -~~~ -
-
-~~~{.swift} - // create a ByteBuffer(:) from an [UInt8] or Data() - var buf = // Get your data - // Get an accessor to the root object inside the buffer. - let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) - // let monster: Monster = getRoot(byteBuffer: &byteBuffer) -~~~ -
- -If you look in the generated files from the schema compiler, you will see it generated -accessors for all non-`deprecated` fields. For example: - -
-~~~{.cpp} - auto hp = monster->hp(); - auto mana = monster->mana(); - auto name = monster->name()->c_str(); -~~~ -
-
-~~~{.java} - short hp = monster.hp(); - short mana = monster.mana(); - String name = monster.name(); -~~~ -
-
-~~~{.kt} - val hp = monster.hp - val mana = monster.mana - val name = monster.name -~~~ -
-
-~~~{.cs} - // For C#, unlike most other languages support by FlatBuffers, most values (except for - // vectors and unions) are available as properties instead of accessor methods. - var hp = monster.Hp - var mana = monster.Mana - var name = monster.Name -~~~ -
-
-~~~{.go} - hp := monster.Hp() - mana := monster.Mana() - name := string(monster.Name()) // Note: `monster.Name()` returns a byte[]. -~~~ -
-
-~~~{.py} - hp = monster.Hp() - mana = monster.Mana() - name = monster.Name() -~~~ -
-
-~~~{.js} - var hp = monster.hp(); - var mana = monster.mana(); - var name = monster.name(); -~~~ -
-
-~~~{.ts} - let hp = monster.hp(); - let mana = monster.mana(); - let name = monster.name(); -~~~ -
-
-~~~{.php} - $hp = $monster->getHp(); - $mana = $monster->getMana(); - $name = monster->getName(); -~~~ -
-
-~~~{.c} - uint16_t hp = ns(Monster_hp(monster)); - uint16_t mana = ns(Monster_mana(monster)); - flatbuffers_string_t name = ns(Monster_name(monster)); -~~~ -
-
-~~~{.dart} - // For Dart, unlike other languages support by FlatBuffers, most values - // are available as properties instead of accessor methods. - var hp = monster.hp; - var mana = monster.mana; - var name = monster.name; -~~~ -
-
-~~~{.lua} - local hp = mon:Hp() - local mana = mon:Mana() - local name = mon:Name() -~~~ -
-
-~~~{.lobster} - let hp = monster.hp - let mana = monster.mana - let name = monster.name -~~~ -
-
-~~~{.rs} - // Get and test some scalar types from the FlatBuffer. - let hp = monster.hp(); - let mana = monster.mana(); - let name = monster.name(); -~~~ -
-
-~~~{.swift} - let hp = monster.hp - let mana = monster.mana - let name = monster.name // returns an optional string -~~~ -
- -These should hold `300`, `150`, and `"Orc"` respectively. - -*Note: The default value `150` wasn't stored in `mana`, but we are still able to retrieve it.* - -To access sub-objects, in the case of our `pos`, which is a `Vec3`: - -
-~~~{.cpp} - auto pos = monster->pos(); - auto x = pos->x(); - auto y = pos->y(); - auto z = pos->z(); -~~~ -
-
-~~~{.java} - Vec3 pos = monster.pos(); - float x = pos.x(); - float y = pos.y(); - float z = pos.z(); -~~~ -
-
-~~~{.kt} - val pos = monster.pos!! - val x = pos.x - val y = pos.y - val z = pos.z -~~~ -
-
-~~~{.cs} - var pos = monster.Pos.Value; - var x = pos.X; - var y = pos.Y; - var z = pos.Z; -~~~ -
-
-~~~{.go} - pos := monster.Pos(nil) - x := pos.X() - y := pos.Y() - z := pos.Z() - - // Note: Whenever you access a new object, like in `Pos()`, a new temporary - // accessor object gets created. If your code is very performance sensitive, - // you can pass in a pointer to an existing `Vec3` instead of `nil`. This - // allows you to reuse it across many calls to reduce the amount of object - // allocation/garbage collection. -~~~ -
-
-~~~{.py} - pos = monster.Pos() - x = pos.X() - y = pos.Y() - z = pos.Z() -~~~ -
-
-~~~{.js} - var pos = monster.pos(); - var x = pos.x(); - var y = pos.y(); - var z = pos.z(); -~~~ -
-
-~~~{.ts} - let pos = monster.pos(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
-
-~~~{.php} - $pos = $monster->getPos(); - $x = $pos->getX(); - $y = $pos->getY(); - $z = $pos->getZ(); -~~~ -
-
-~~~{.c} - ns(Vec3_struct_t) pos = ns(Monster_pos(monster)); - float x = ns(Vec3_x(pos)); - float y = ns(Vec3_y(pos)); - float z = ns(Vec3_z(pos)); -~~~ -
-
-~~~{.dart} - myGame.Vec3 pos = monster.pos; - double x = pos.x; - double y = pos.y; - double z = pos.z; -~~~ -
-
-~~~{.lua} - local pos = mon:Pos() - local x = pos:X() - local y = pos:Y() - local z = pos:Z() -~~~ -
-
-~~~{.lobster} - let pos = monster.pos - let x = pos.x - let y = pos.y - let z = pos.z -~~~ -
-
-~~~{.rs} - let pos = monster.pos().unwrap(); - let x = pos.x(); - let y = pos.y(); - let z = pos.z(); -~~~ -
-
-~~~{.swift} - let pos = monster.pos - let x = pos.x - let y = pos.y - let z = pos.z -~~~ -
- -`x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0`, respectively. - -*Note: Had we not set `pos` during serialization, it would be a `null`-value.* - -Similarly, we can access elements of the inventory `vector` by indexing it. You -can also iterate over the length of the array/vector representing the -FlatBuffers `vector`. - -
-~~~{.cpp} - auto inv = monster->inventory(); // A pointer to a `flatbuffers::Vector<>`. - auto inv_len = inv->size(); - auto third_item = inv->Get(2); -~~~ -
-
-~~~{.java} - int invLength = monster.inventoryLength(); - byte thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.kotlin} - val invLength = monster.inventoryLength - val thirdItem = monster.inventory(2)!! -~~~ -
-
-~~~{.cs} - int invLength = monster.InventoryLength; - var thirdItem = monster.Inventory(2); -~~~ -
-
-~~~{.go} - invLength := monster.InventoryLength() - thirdItem := monster.Inventory(2) -~~~ -
-
-~~~{.py} - inv_len = monster.InventoryLength() - third_item = monster.Inventory(2) -~~~ -
-
-~~~{.js} - var invLength = monster.inventoryLength(); - var thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.ts} - let invLength = monster.inventoryLength(); - let thirdItem = monster.inventory(2); -~~~ -
-
-~~~{.php} - $inv_len = $monster->getInventoryLength(); - $third_item = $monster->getInventory(2); -~~~ -
-
-~~~{.c} - // If `inv` hasn't been set, it will be null. It is valid get - // the length of null which will be 0, useful for iteration. - flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster)); - size_t inv_len = flatbuffers_uint8_vec_len(inv); -~~~ -
-
-~~~{.dart} - int invLength = monster.inventory.length; - var thirdItem = monster.inventory[2]; -~~~ -
-
-~~~{.lua} - local invLength = mon:InventoryLength() - local thirdItem = mon:Inventory(3) -- Lua is 1-based -~~~ -
-
-~~~{.lobster} - let inv_len = monster.inventory_length - let third_item = monster.inventory(2) -~~~ -
-
-~~~{.rs} - // Get and test an element from the `inventory` FlatBuffer's `vector`. - let inv = monster.inventory().unwrap(); - - // Note that this vector is returned as a slice, because direct access for - // this type, a `u8` vector, is safe on all platforms: - let third_item = inv[2]; -~~~ -
-
-~~~{.swift} - // Get a the count of objects in the vector - let count = monster.inventoryCount - - // get item at index 4 - let object = monster.inventory(at: 4) - - // or you can fetch the entire array - let inv = monster.inventory - // inv[4] should equal object -~~~ -
- -For `vector`s of `table`s, you can access the elements like any other vector, -except you need to handle the result as a FlatBuffer `table`: - -
-~~~{.cpp} - auto weapons = monster->weapons(); // A pointer to a `flatbuffers::Vector<>`. - auto weapon_len = weapons->size(); - auto second_weapon_name = weapons->Get(1)->name()->str(); - auto second_weapon_damage = weapons->Get(1)->damage() -~~~ -
-
-~~~{.java} - int weaponsLength = monster.weaponsLength(); - String secondWeaponName = monster.weapons(1).name(); - short secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.kt} - val weaponsLength = monster.weaponsLength - val secondWeaponName = monster.weapons(1)!!.name - val secondWeaponDamage = monster.weapons(1)!!.damage -~~~ -
-
-~~~{.cs} - int weaponsLength = monster.WeaponsLength; - var secondWeaponName = monster.Weapons(1).Name; - var secondWeaponDamage = monster.Weapons(1).Damage; -~~~ -
-
-~~~{.go} - weaponLength := monster.WeaponsLength() - weapon := new(sample.Weapon) // We need a `sample.Weapon` to pass into `monster.Weapons()` - // to capture the output of the function. - if monster.Weapons(weapon, 1) { - secondWeaponName := weapon.Name() - secondWeaponDamage := weapon.Damage() - } -~~~ -
-
-~~~{.py} - weapons_length = monster.WeaponsLength() - second_weapon_name = monster.Weapons(1).Name() - second_weapon_damage = monster.Weapons(1).Damage() -~~~ -
-
-~~~{.js} - var weaponsLength = monster.weaponsLength(); - var secondWeaponName = monster.weapons(1).name(); - var secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.ts} - let weaponsLength = monster.weaponsLength(); - let secondWeaponName = monster.weapons(1).name(); - let secondWeaponDamage = monster.weapons(1).damage(); -~~~ -
-
-~~~{.php} - $weapons_len = $monster->getWeaponsLength(); - $second_weapon_name = $monster->getWeapons(1)->getName(); - $second_weapon_damage = $monster->getWeapons(1)->getDamage(); -~~~ -
-
-~~~{.c} - ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster)); - size_t weapons_len = ns(Weapon_vec_len(weapons)); - // We can use `const char *` instead of `flatbuffers_string_t`. - const char *second_weapon_name = ns(Weapon_name(ns(Weapon_vec_at(weapons, 1)))); - uint16_t second_weapon_damage = ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1)))); -~~~ -
-
-~~~{.dart} - int weaponsLength = monster.weapons.length; - var secondWeaponName = monster.weapons[1].name; - var secondWeaponDamage = monster.Weapons[1].damage; -~~~ -
-
-~~~{.lua} - local weaponsLength = mon:WeaponsLength() - local secondWeaponName = mon:Weapon(2):Name() - local secondWeaponDamage = mon:Weapon(2):Damage() -~~~ -
-
-~~~{.lobster} - let weapons_length = monster.weapons_length - let second_weapon_name = monster.weapons(1).name - let second_weapon_damage = monster.weapons(1).damage -~~~ -
-
-~~~{.rs} - // Get and test the `weapons` FlatBuffers's `vector`. - let weps = monster.weapons().unwrap(); - let weps_len = weps.len(); - - let wep2 = weps.get(1); - let second_weapon_name = wep2.name(); - let second_weapon_damage = wep2.damage(); -~~~ -
-
-~~~{.swift} - // Get the count of weapon objects - let wepsCount = monster.weaponsCount - - let weapon2 = monster.weapons(at: 1) - let weaponName = weapon2.name - let weaponDmg = weapon2.damage -~~~ -
- -Last, we can access our `Equipped` FlatBuffer `union`. Just like when we created -the `union`, we need to get both parts of the `union`: the type and the data. - -We can access the type to dynamically cast the data as needed (since the -`union` only stores a FlatBuffer `table`). - -
-~~~{.cpp} - auto union_type = monster->equipped_type(); - - if (union_type == Equipment_Weapon) { - auto weapon = static_cast(monster->equipped()); // Requires `static_cast` - // to type `const Weapon*`. - - auto weapon_name = weapon->name()->str(); // "Axe" - auto weapon_damage = weapon->damage(); // 5 - } -~~~ -
-
-~~~{.java} - int unionType = monster.EquippedType(); - - if (unionType == Equipment.Weapon) { - Weapon weapon = (Weapon)monster.equipped(new Weapon()); // Requires explicit cast - // to `Weapon`. - - String weaponName = weapon.name(); // "Axe" - short weaponDamage = weapon.damage(); // 5 - } -~~~ -
-
-~~~{.kt} - val unionType = monster.EquippedType - - if (unionType == Equipment.Weapon) { - val weapon = monster.equipped(Weapon()) as Weapon // Requires explicit cast - // to `Weapon`. - - val weaponName = weapon.name // "Axe" - val weaponDamage = weapon.damage // 5 - } -~~~ -
-
-~~~{.cs} - var unionType = monster.EquippedType; - - if (unionType == Equipment.Weapon) { - var weapon = monster.Equipped().Value; - - var weaponName = weapon.Name; // "Axe" - var weaponDamage = weapon.Damage; // 5 - } -~~~ -
-
-~~~{.go} - // We need a `flatbuffers.Table` to capture the output of the - // `monster.Equipped()` function. - unionTable := new(flatbuffers.Table) - - if monster.Equipped(unionTable) { - unionType := monster.EquippedType() - - if unionType == sample.EquipmentWeapon { - // Create a `sample.Weapon` object that can be initialized with the contents - // of the `flatbuffers.Table` (`unionTable`), which was populated by - // `monster.Equipped()`. - unionWeapon = new(sample.Weapon) - unionWeapon.Init(unionTable.Bytes, unionTable.Pos) - - weaponName = unionWeapon.Name() - weaponDamage = unionWeapon.Damage() - } - } -~~~ -
-
-~~~{.py} - union_type = monster.EquippedType() - - if union_type == MyGame.Sample.Equipment.Equipment().Weapon: - # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used to - # initialize a `MyGame.Sample.Weapon.Weapon()`. - union_weapon = MyGame.Sample.Weapon.Weapon() - union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos) - - weapon_name = union_weapon.Name() // 'Axe' - weapon_damage = union_weapon.Damage() // 5 -~~~ -
-
-~~~{.js} - var unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - var weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - var weaponDamage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.ts} - let unionType = monster.equippedType(); - - if (unionType == MyGame.Sample.Equipment.Weapon) { - let weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); // 'Axe' - let weaponDamage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5 - } -~~~ -
-
-~~~{.php} - $union_type = $monster->getEquippedType(); - - if ($union_type == \MyGame\Sample\Equipment::Weapon) { - $weapon_name = $monster->getEquipped(new \MyGame\Sample\Weapon())->getName(); // "Axe" - $weapon_damage = $monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage(); // 5 - } -~~~ -
-
-~~~{.c} - // Access union type field. - if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) { - // Cast to appropriate type: - // C allows for silent void pointer assignment, so we need no explicit cast. - ns(Weapon_table_t) weapon = ns(Monster_equipped(monster)); - const char *weapon_name = ns(Weapon_name(weapon)); // "Axe" - uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5 - } -~~~ -
-
-~~~{.dart} - var unionType = monster.equippedType.value; - - if (unionType == myGame.EquipmentTypeId.Weapon.value) { - myGame.Weapon weapon = mon.equipped as myGame.Weapon; - - var weaponName = weapon.name; // "Axe" - var weaponDamage = weapon.damage; // 5 - } -~~~ -
-
-~~~{.lua} - local unionType = mon:EquippedType() - - if unionType == equipment.Weapon then - local unionWeapon = weapon.New() - unionWeapon:Init(mon:Equipped().bytes, mon:Equipped().pos) - - local weaponName = unionWeapon:Name() -- 'Axe' - local weaponDamage = unionWeapon:Damage() -- 5 - end -~~~ -
-
-~~~{.lobster} - union_type = monster.equipped_type - - if union_type == MyGame_Sample_Equipment_Weapon: - // `monster.equipped_as_Weapon` returns a FlatBuffer handle much like normal table fields, - // but this is only valid to call if we already know it is the correct type. - let union_weapon = monster.equipped_as_Weapon - - let weapon_name = union_weapon.name // "Axe" - let weapon_damage = union_weapon.damage // 5 -~~~ -
-
-~~~{.rs} - // Get and test the `Equipment` union (`equipped` field). - // `equipped_as_weapon` returns a FlatBuffer handle much like normal table - // fields, but this will return `None` if the union is not actually of that - // type. - if monster.equipped_type() == Equipment::Weapon { - let equipped = monster.equipped_as_weapon().unwrap(); - let weapon_name = equipped.name(); - let weapon_damage = equipped.damage(); -~~~ -
-
-~~~{.swift} - // Get and check if the monster has an equipped item - if monster.equippedType == .weapon { - let _weapon = monster.equipped(type: Weapon.self) - let name = _weapon.name // should return "Axe" - let dmg = _weapon.damage // should return 5 - } -~~~ -
- -## Mutating FlatBuffers - -As you saw above, typically once you have created a FlatBuffer, it is read-only -from that moment on. There are, however, cases where you have just received a -FlatBuffer, and you'd like to modify something about it before sending it on to -another recipient. With the above functionality, you'd have to generate an -entirely new FlatBuffer, while tracking what you modified in your own data -structures. This is inconvenient. - -For this reason FlatBuffers can also be mutated in-place. While this is great -for making small fixes to an existing buffer, you generally want to create -buffers from scratch whenever possible, since it is much more efficient and the -API is much more general purpose. - -To get non-const accessors, invoke `flatc` with `--gen-mutable`. - -Similar to how we read fields using the accessors above, we can now use the -mutators like so: - -
-~~~{.cpp} - auto monster = GetMutableMonster(buffer_pointer); // non-const - monster->mutate_hp(10); // Set the table `hp` field. - monster->mutable_pos()->mutate_z(4); // Set struct field. - monster->mutable_inventory()->Mutate(0, 1); // Set vector element. -~~~ -
-
-~~~{.java} - Monster monster = Monster.getRootAsMonster(buf); - monster.mutateHp(10); // Set table field. - monster.pos().mutateZ(4); // Set struct field. - monster.mutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.kt} - val monster = Monster.getRootAsMonster(buf) - monster.mutateHp(10) // Set table field. - monster.pos!!.mutateZ(4) // Set struct field. - monster.mutateInventory(0, 1) // Set vector element. -~~~ -
-
-~~~{.cs} - var monster = Monster.GetRootAsMonster(buf); - monster.MutateHp(10); // Set table field. - monster.Pos.MutateZ(4); // Set struct field. - monster.MutateInventory(0, 1); // Set vector element. -~~~ -
-
-~~~{.go} - -~~~ -
-
-~~~{.py} - -~~~ -
-
-~~~{.js} - -~~~ -
-
-~~~{.ts} - -~~~ -
-
-~~~{.php} - -~~~ -
-
-~~~{.c} - -~~~ -
-
-~~~{.dart} - -~~~ -
-
-~~~{.lua} - -~~~ -
-
-~~~{.lobster} - -~~~ -
-
-~~~{.rs} - -~~~ -
-
-~~~{.swift} - let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf)) - monster.mutate(hp: 10) // mutates a value in a table - /// to mutate structs in swift you have to use the mutable accessors - monster.mutablePos.mutate(z: 4) // mutates a value in a struct - monster.mutate(inventory: 6, at index: 0) // mutates a value in an Scalar array -~~~ -
- -We use the somewhat verbose term `mutate` instead of `set` to indicate that this -is a special use case, not to be confused with the default way of constructing -FlatBuffer data. - -After the above mutations, you can send on the FlatBuffer to a new recipient -without any further work! - -Note that any `mutate` functions on a table will return a boolean, which is -`false` if the field we're trying to set is not present in the buffer. Fields -are not present if they weren't set, or even if they happen to be equal to -the default value. For example, in the creation code above, the `mana` -field is equal to `150`, which is the default value, so it was never stored in -the buffer. Trying to call the corresponding `mutate` method for `mana` on such -data will return `false`, and the value won't actually be modified! - -One way to solve this is to call `ForceDefaults` on a FlatBufferBuilder to -force all fields you set to actually be written. This, of course, increases the -size of the buffer somewhat, but this may be acceptable for a mutable buffer. - -If this is not sufficient, other ways of mutating FlatBuffers may be supported -in your language through an object based API (`--gen-object-api`) or reflection. -See the individual language documents for support. - -## Using `flatc` as a JSON Conversion Tool - -If you are working with C, C++, or Lobster, you can parse JSON at runtime. -If your language does not support JSON at the moment, `flatc` may provide an -alternative. Using `flatc` is often the preferred method, as it doesn't require you to -add any new code to your program. It is also efficient, since you can ship with -the binary data. The drawback is that it requires an extra step for your -users/developers to perform (although it may be able to be automated -as part of your compilation). - -#### JSON to binary representation - -Let's say you have a JSON file that describes your monster. In this example, -we will use the file `flatbuffers/samples/monsterdata.json`. - -Here are the contents of the file: - -~~~{.json} -{ - "pos": { - "x": 1.0, - "y": 2.0, - "z": 3.0 - }, - "hp": 300, - "name": "Orc", - "weapons": [ - { - "name": "axe", - "damage": 100 - }, - { - "name": "bow", - "damage": 90 - } - ], - "equipped_type": "Weapon", - "equipped": { - "name": "bow", - "damage": 90 - } -} -~~~ - -You can run this file through the `flatc` compiler with the `-b` flag and -our `monster.fbs` schema to produce a FlatBuffer binary file. - -~~~{.sh} -./../flatc --binary monster.fbs monsterdata.json -~~~ - -The output of this will be a file `monsterdata.bin`, which will contain the -FlatBuffer binary representation of the contents from our `.json` file. - -
-*Note: If you're working in C++, you can also parse JSON at runtime. See the -[Use in C++](@ref flatbuffers_guide_use_cpp) section of the Programmer's -Guide for more information.* -
-
-*Note: If you're working in C, the `flatcc --json` (not `flatc`) -compiler will generate schema specific high performance json parsers and -printers that you can compile and use at runtime. The `flatc` compiler (not -`flatcc`) on the other hand, is still useful for general offline json to -flatbuffer conversion from a given schema. There are no current plans -for `flatcc` to support this.* -
-
-*Note: If you're working in Lobster, you can also parse JSON at runtime. See the -[Use in Lobster](@ref flatbuffers_guide_use_lobster) section of the Programmer's -Guide for more information.* -
- -#### FlatBuffer binary to JSON - -Converting from a FlatBuffer binary representation to JSON is supported as well: -~~~{.sh} -./../flatc --json --raw-binary monster.fbs -- monsterdata.bin -~~~ -This will convert `monsterdata.bin` back to its original JSON representation. -You need to pass the corresponding FlatBuffers schema so that flatc knows how to -interpret the binary buffer. Since `monster.fbs` does not specify an explicit -`file_identifier` for binary buffers, `flatc` needs to be forced into reading -the `.bin` file using the `--raw-binary` option. - -The FlatBuffer binary representation does not explicitly encode default values, -therefore they are not present in the resulting JSON unless you specify -`--defaults-json`. - -If you intend to process the JSON with other tools, you may consider switching -on `--strict-json` so that identifiers are quoted properly. - -*Note: The resulting JSON file is not necessarily identical with the original JSON. -If the binary representation contains floating point numbers, floats and doubles -are rounded to 6 and 12 digits, respectively, in order to represent them as -decimals in the JSON document.* - -## Advanced Features for Each Language - -### Vector of Unions - -Some languages support storing unions directly in a vector. - -~~~ -// File found in tests/union_vector/union_vector.fbs -namespace Example.VectorOfUnions; - -// Demonstrates the ability to have vectors of unions, and also to -// store structs and strings in unions. - -table Attacker { - sword_attack_damage: int; -} - -struct Rapunzel { - hair_length: int; -} - -struct BookReader { - books_read: int; -} - -union Character { - MuLan: Attacker, // Can have name be different from type. - Rapunzel, // Or just both the same, as before. - Belle: BookReader, - BookFan: BookReader, - Other: string, - Unused: string -} - -table Movie { - main_character: Character; - characters: [Character]; -} -~~~ - -#### Creating - -Analagously to how a union adds two fields to a table a vector of unions creates two different vectors: -one for the union data and one for the data types. - -
-C++ supports vectors of unions, but it isn't currently documented. -
-
-Typescript supports vectors of unions, but it isn't currently documented. -
-
-PHP supports vectors of unions, but it isn't currently documented. -
-
-Java supports vectors of unions, but it isn't currently documented. -
-
-~~~{.cs} -using Google.FlatBuffers; -using Example.VectorOfUnions; - -var fbb = new FlatBufferBuilder(100); - -var characterTypes = new[] -{ - Character.MuLan, - Character.Belle, - Character.Other, -}; -var characterTypesOffset = Movie.CreateCharactersTypeVector(fbb, characterTypes); - -var characters = new[] -{ - Attacker.CreateAttacker(fbb, 10).Value, - BookReader.CreateBookReader(fbb, 20).Value, - fbb.CreateSharedString("Chip").Value, -}; -var charactersOffset = Movie.CreateCharactersVector(fbb, characters); - -var movieOffset = Movie.CreateMovie( - fbb, - Character.Rapunzel, - rapunzel, - characterTypesOffset, - charactersOffset); -Movie.FinishMovieBuffer(fbb, movieOffset); -~~~ -
-
-Kotlin supports vectors of unions, but it isn't currently documented. -
-
-Swift supports vectors of unions, but it isn't currently documented. -
- -#### Reading -
-~~~{.cs} -var movie = Movie.GetRootAsMovie(fbb.DataBuffer); - -for (var i = 0; i <= movie.CharactersLength; i++) -{ - if (movie.CharactersType(i) == Character.MuLan) - { - var mulanSwordDamage = movie.Characters(i).Value.SwordAttackDamage; - } - else if (movie.CharactersType(i) == Character.Belle) - { - var belleBooksRead = movie.Characters(i).Value.BooksRead; - } - else if (movie.CharactersType(i) == Character.Other) - { - var otherStr = movie.CharactersAsString(i); - } -} -~~~ -
- -### Further Reading - -Each language has a dedicated `Use in XXX` page in the Programmer's Guide -to cover the nuances of FlatBuffers in that language. - -For your chosen language, see: - -
-[Use in C++](@ref flatbuffers_guide_use_cpp) -
-
-[Use in Java](@ref flatbuffers_guide_use_java) -
-
-[Use in Kotlin](@ref flatbuffers_guide_use_kotlin) -
-
-[Use in C#](@ref flatbuffers_guide_use_c-sharp) -
-
-[Use in Go](@ref flatbuffers_guide_use_go) -
-
-[Use in Python](@ref flatbuffers_guide_use_python) -
-
-[Use in JavaScript](@ref flatbuffers_guide_use_javascript) -
-
-[Use in TypeScript](@ref flatbuffers_guide_use_typescript) -
-
-[Use in PHP](@ref flatbuffers_guide_use_php) -
-
-[Use in C](@ref flatbuffers_guide_use_c) -
-
-[Use in Dart](@ref flatbuffers_guide_use_dart) -
-
-[Use in Lua](@ref flatbuffers_guide_use_lua) -
-
-[Use in Lobster](@ref flatbuffers_guide_use_lobster) -
-
-[Use in Rust](@ref flatbuffers_guide_use_rust) -
-
-[Use in Swift](@ref flatbuffers_guide_use_swift) -
-
diff --git a/docs-old/source/TypeScriptUsage.md b/docs-old/source/TypeScriptUsage.md deleted file mode 100644 index 0dd1da2eb22..00000000000 --- a/docs-old/source/TypeScriptUsage.md +++ /dev/null @@ -1,96 +0,0 @@ -Use in TypeScript {#flatbuffers_guide_use_typescript} -================= - -## Before you get started - -Before diving into the FlatBuffers usage in TypeScript, it should be noted that -the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide to -general FlatBuffers usage in all of the supported languages -(including TypeScript). This page is specifically designed to cover the nuances -of FlatBuffers usage in TypeScript. - -You should also have read the [Building](@ref flatbuffers_guide_building) -documentation to build `flatc` and should be familiar with -[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler) and -[Writing a schema](@ref flatbuffers_guide_writing_schema). - -## FlatBuffers TypeScript library code location - -The code for the FlatBuffers TypeScript library can be found at -https://www.npmjs.com/package/flatbuffers. - -## Testing the FlatBuffers TypeScript library - -To run the tests, use the [TypeScriptTest.py](https://github.com/google/ -flatbuffers/blob/master/tests/TypeScriptTest.py) Python3 script. - -*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).* - -## Using the FlatBuffers TypeScript library - -*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth -example of how to use FlatBuffers in TypeScript.* - -FlatBuffers supports both reading and writing FlatBuffers in TypeScript. - -To use FlatBuffers in your own code, first generate TypeScript classes from your -schema with the `--ts` option to `flatc`. Then you can include both FlatBuffers -and the generated code to read or write a FlatBuffer. - -For example, here is how you would read a FlatBuffer binary file in TypeScript: -First, include the library and generated code. Then read the file into an -`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass -the ByteBuffer to the `getRootAsMonster` function. - -~~~{.ts} - import * as flatbuffers from 'flatbuffers'; - - import { MyGame } from './monster_generated'; - - let data = new Uint8Array(fs.readFileSync('monster.dat')); - let buf = new flatbuffers.ByteBuffer(data); - - let monster = MyGame.Example.Monster.getRootAsMonster(buf); -~~~ - -Now you can access values like this: - -~~~{.ts} - let hp = monster.hp(); - let pos = monster.pos(); -~~~ - -## Object based API - -FlatBuffers is all about memory efficiency, which is why its base API is written -around using as little as possible of it. This does make the API clumsier -(requiring pre-order construction of all data, and making mutation harder). - -For times when efficiency is less important a more convenient object based API -can be used (through `--gen-object-api`) that is able to unpack & pack a -FlatBuffer into objects and standard TS types. - -To use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.ts} - // Autogenerated class from table Monster. - let monsterobj = new MonsterT(); - - // Deserialize from buffer into object. - Monster.getRootAsMonster(flatbuffer).unpackTo(monsterobj); - // or - let monsterobj = Monster.getRootAsMonster(flatbuffer).unpack(); - - // Update object directly like a regular TS class instance. - console.log(monsterobj.name); - monsterobj.name = "Bob"; - - // Serialize into new flatbuffer. - let fbb = new flatbuffers.Builder(1); - Monster.finishMonsterBuffer(fbb, monsterobj.pack(fbb)); -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -## Text parsing FlatBuffers in TypeScript - -There currently is no support for parsing text (Schema's and JSON) directly -from TypeScript. diff --git a/docs-old/source/WhitePaper.md b/docs-old/source/WhitePaper.md deleted file mode 100644 index dbad2cb35a0..00000000000 --- a/docs-old/source/WhitePaper.md +++ /dev/null @@ -1,128 +0,0 @@ -FlatBuffers white paper {#flatbuffers_white_paper} -======================= - -This document tries to shed some light on to the "why" of FlatBuffers, a -new serialization library. - -## Motivation - -Back in the good old days, performance was all about instructions and -cycles. Nowadays, processing units have run so far ahead of the memory -subsystem, that making an efficient application should start and finish -with thinking about memory. How much you use of it. How you lay it out -and access it. How you allocate it. When you copy it. - -Serialization is a pervasive activity in a lot programs, and a common -source of memory inefficiency, with lots of temporary data structures -needed to parse and represent data, and inefficient allocation patterns -and locality. - -If it would be possible to do serialization with no temporary objects, -no additional allocation, no copying, and good locality, this could be -of great value. The reason serialization systems usually don't manage -this is because it goes counter to forwards/backwards compatibility, and -platform specifics like endianness and alignment. - -FlatBuffers is what you get if you try anyway. - -In particular, FlatBuffers focus is on mobile hardware (where memory -size and memory bandwidth is even more constrained than on desktop -hardware), and applications that have the highest performance needs: -games. - -## FlatBuffers - -*This is a summary of FlatBuffers functionality, with some rationale. -A more detailed description can be found in the FlatBuffers -documentation.* - -### Summary - -A FlatBuffer is a binary buffer containing nested objects (structs, -tables, vectors,..) organized using offsets so that the data can be -traversed in-place just like any pointer-based data structure. Unlike -most in-memory data structures however, it uses strict rules of -alignment and endianness (always little) to ensure these buffers are -cross platform. Additionally, for objects that are tables, FlatBuffers -provides forwards/backwards compatibility and general optionality of -fields, to support most forms of format evolution. - -You define your object types in a schema, which can then be compiled to -C++ or Java for low to zero overhead reading & writing. -Optionally, JSON data can be dynamically parsed into buffers. - -### Tables - -Tables are the cornerstone of FlatBuffers, since format evolution is -essential for most applications of serialization. Typically, dealing -with format changes is something that can be done transparently during -the parsing process of most serialization solutions out there. -But a FlatBuffer isn't parsed before it is accessed. - -Tables get around this by using an extra indirection to access fields, -through a *vtable*. Each table comes with a vtable (which may be shared -between multiple tables with the same layout), and contains information -where fields for this particular kind of instance of vtable are stored. -The vtable may also indicate that the field is not present (because this -FlatBuffer was written with an older version of the software, or simply -because the information was not necessary for this instance, or deemed -deprecated), in which case a default value is returned. - -Tables have a low overhead in memory (since vtables are small and -shared) and in access cost (an extra indirection), but provide great -flexibility. Tables may even cost less memory than the equivalent -struct, since fields do not need to be stored when they are equal to -their default. - -FlatBuffers additionally offers "naked" structs, which do not offer -forwards/backwards compatibility, but can be even smaller (useful for -very small objects that are unlikely to change, like e.g. a coordinate -pair or a RGBA color). - -### Schemas - -While schemas reduce some generality (you can't just read any data -without having its schema), they have a lot of upsides: - -- Most information about the format can be factored into the generated - code, reducing memory needed to store data, and time to access it. - -- The strong typing of the data definitions means less error - checking/handling at runtime (less can go wrong). - -- A schema enables us to access a buffer without parsing. - -FlatBuffer schemas are fairly similar to those of the incumbent, -Protocol Buffers, and generally should be readable to those familiar -with the C family of languages. We chose to improve upon the features -offered by .proto files in the following ways: - -- Deprecation of fields instead of manual field id assignment. - Extending an object in a .proto means hunting for a free slot among - the numbers (preferring lower numbers since they have a more compact - representation). Besides being inconvenient, it also makes removing - fields problematic: you either have to keep them, not making it - obvious that this field shouldn't be read/written anymore, and still - generating accessors. Or you remove it, but now you risk that - there's still old data around that uses that field by the time - someone reuses that field id, with nasty consequences. - -- Differentiating between tables and structs (see above). Effectively - all table fields are `optional`, and all struct fields are - `required`. - -- Having a native vector type instead of `repeated`. This gives you a - length without having to collect all items, and in the case of - scalars provides for a more compact representation, and one that - guarantees adjacency. - -- Having a native `union` type instead of using a series of `optional` - fields, all of which must be checked individually. - -- Being able to define defaults for all scalars, instead of having to - deal with their optionality at each access. - -- A parser that can deal with both schemas and data definitions (JSON - compatible) uniformly. - -
diff --git a/docs-old/source/doxyfile b/docs-old/source/doxyfile deleted file mode 100644 index 9541aaff7f2..00000000000 --- a/docs-old/source/doxyfile +++ /dev/null @@ -1,2375 +0,0 @@ -# Doxyfile 1.8.5 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = "FlatBuffers" - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = - -# With the PROJECT_LOGO tag one can specify an logo or icon that is included in -# the documentation. The maximum height of the logo should not exceed 55 pixels -# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo -# to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = ".." - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese- -# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en, -# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish, -# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, -# Turkish, Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = NO - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a -# new page for each member. If set to NO, the documentation of a member will be -# part of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 2 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. -# -# Note For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by by putting a % sign in front of the word -# or globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = NO # Due to the multiple languages included in the API - # reference for FlatBuffers, the Auto-links were - # wrong more often than not. - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = NO - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = NO - -# This flag is only useful for Objective-C code. When set to YES local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO these classes will be included in the various overviews. This option has -# no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO the members will appear in declaration order. -# The default value is: NO. - -SORT_BRIEF_DOCS = YES - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the -# todo list. This list is created by putting \todo commands in the -# documentation. -# The default value is: YES. - -GENERATE_TODOLIST = NO - -# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the -# test list. This list is created by putting \test commands in the -# documentation. -# The default value is: YES. - -GENERATE_TESTLIST = NO - -# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = NO - -# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if ... \endif and \cond -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES the list -# will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = doxygen_layout.xml - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. Do not use file names with spaces, bibtex cannot handle them. See -# also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = NO - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO doxygen will only warn about wrong or incomplete parameter -# documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. -# Note: If this tag is empty the current directory is searched. - -INPUT = "FlatBuffers.md" \ - "Building.md" \ - "Compiler.md" \ - "Schemas.md" \ - "CppUsage.md" \ - "CUsage.md" \ - "DartUsage.md" \ - "GoUsage.md" \ - "JavaUsage.md" \ - "CsharpUsage.md" \ - "SwiftUsage.md" \ - "JavaScriptUsage.md" \ - "TypeScriptUsage.md" \ - "PHPUsage.md" \ - "PythonUsage.md" \ - "LuaUsage.md" \ - "LobsterUsage.md" \ - "RustUsage.md" \ - "Support.md" \ - "Benchmarks.md" \ - "WhitePaper.md" \ - "FlexBuffers.md" \ - "Internals.md" \ - "IntermediateRepresentation.md" \ - "Grammar.md" \ - "../../CONTRIBUTING.md" \ - "Tutorial.md" \ - "GoApi.md" \ - "gRPC/CppUsage.md" \ - "groups" \ - "../../java/com/google/flatbuffers" \ - "../../python/flatbuffers/builder.py" \ - "../../js/flatbuffers.js" \ - "../../php/FlatbufferBuilder.php" \ - "../../net/FlatBuffers/FlatBufferBuilder.cs" - "../../net/FlatBuffers/FlatBufferVerify.cs" \ - "../../include/flatbuffers/flatbuffers.h" \ - "../../go/builder.go" \ - "../../rust/flatbuffers/src/builder.rs" - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank the -# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, -# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, -# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, -# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, -# *.qsf, *.as and *.js. - -FILE_PATTERNS = *.c \ - *.cc \ - *.cxx \ - *.cpp \ - *.c++ \ - *.java \ - *.ii \ - *.ixx \ - *.ipp \ - *.i++ \ - *.inl \ - *.idl \ - *.ddl \ - *.odl \ - *.h \ - *.hh \ - *.hxx \ - *.hpp \ - *.h++ \ - *.cs \ - *.d \ - *.php \ - *.php4 \ - *.php5 \ - *.phtml \ - *.inc \ - *.m \ - *.markdown \ - *.md \ - *.mm \ - *.dox \ - *.py \ - *.f90 \ - *.f \ - *.for \ - *.tcl \ - *.vhd \ - *.vhdl \ - *.ucf \ - *.qsf \ - *.as \ - *.js \ - *.go - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = *_test.py | - __init__.py - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = "GoApi_generated.txt" "../../grpc/samples" - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = *.cpp *.h *.txt *.fbs - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = YES - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# -# -# where is the value of the INPUT_FILTER tag, and is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = *.py=py_filter - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER ) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = FlatBuffers.md - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = NO - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES, then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = YES - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = ../header.html - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = ../footer.html - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user- -# defined cascading style sheet that is included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefor more robust against future updates. -# Doxygen will copy the style sheet file to the output directory. For an example -# see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = style.css - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = "../images/fpl_logo_small.png" \ - "../images/ftv2mnode.png" \ - "../images/ftv2pnode.png" - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the stylesheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to NO can help when comparing the output of multiple runs. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = YES - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler ( hhc.exe). If non-empty -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated ( -# YES) or that it should be included in the master .chm file ( NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated ( -# YES) or a normal table of contents ( NO) in the .chm file. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = YES - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using prerendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use + S -# (what the is depends on the OS and browser, but it is typically -# , /