summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlon Zakai <alonzakai@gmail.com>2015-12-29 21:15:26 -0800
committerAlon Zakai <alonzakai@gmail.com>2015-12-29 22:16:58 -0800
commit44a8aeaf5820ee06e8c6dbc061d131d7b4d39cd3 (patch)
treeb2a048c9a647869eb29d0677ed56e249db9b9dc8
parentfb895476f8ba11c27a4732be28ec53356f6d759f (diff)
downloadbinaryen-44a8aeaf5820ee06e8c6dbc061d131d7b4d39cd3.tar.gz
binaryen-44a8aeaf5820ee06e8c6dbc061d131d7b4d39cd3.tar.bz2
binaryen-44a8aeaf5820ee06e8c6dbc061d131d7b4d39cd3.zip
BufferWithRandomAccess
-rw-r--r--src/wasm-binary.h62
1 files changed, 60 insertions, 2 deletions
diff --git a/src/wasm-binary.h b/src/wasm-binary.h
index 25225579b..12d1a2083 100644
--- a/src/wasm-binary.h
+++ b/src/wasm-binary.h
@@ -29,6 +29,64 @@
namespace wasm {
+struct LEB128 {
+ int32_t value;
+ LEB128(int32_t value) : value(value) {}
+};
+
+// We mostly stream into a buffer as we create the binary format, however,
+// sometimes we need to backtrack and write to a location behind us.
+class BufferWithRandomAccess : public std::vector<unsigned char> {
+public:
+ BufferWithRandomAccess& operator<<(int8_t x) {
+ push_back(x);
+ return *this;
+ }
+ BufferWithRandomAccess& operator<<(int16_t x) {
+ push_back(x & 0xff);
+ push_back(x >> 8);
+ return *this;
+ }
+ BufferWithRandomAccess& operator<<(int32_t x) {
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff);
+ return *this;
+ }
+ BufferWithRandomAccess& operator<<(int64_t x) {
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff); x >>= 8;
+ push_back(x & 0xff);
+ return *this;
+ }
+ BufferWithRandomAccess& operator<<(LEB128 x) {
+ // XXX TODO
+ magic
+ return *this;
+ }
+
+ void writeAt(size_t i, int16_t x) {
+ (*this)[i] = x & 0xff;
+ (*this)[i+1] = x >> 8;
+ }
+ void writeAt(size_t i, int32_t x) {
+ (*this)[i] = x & 0xff; x >>= 8;
+ (*this)[i+1] = x & 0xff; x >>= 8;
+ (*this)[i+2] = x & 0xff; x >>= 8;
+ (*this)[i+3] = x & 0xff;
+ }
+
+ friend ostream& operator<<(ostream& o, BufferWithRandomAccess& b) {
+ for (auto c : b) o << c;
+ }
+};
+
enum Section {
Memory = 0,
Signatures = 1,
@@ -215,10 +273,10 @@ char binaryWasmType(WasmType type) {
class WasmBinaryWriter : public WasmVisitor<void> {
Module* wasm;
- ostream& o;
+ BufferWithRandomAccess& o;
public:
- WasmBinaryWriter(Module* wasm, ostream& o) : wasm(wasm), o(o) {}
+ WasmBinaryWriter(Module* wasm, BufferWithRandomAccess& o) : wasm(wasm), o(o) {}
void write() {
writeMemory();