1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors 2 // Licensed under the MIT License: 3 // 4 // Permission is hereby granted, free of charge, to any person obtaining a copy 5 // of this software and associated documentation files (the "Software"), to deal 6 // in the Software without restriction, including without limitation the rights 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 // copies of the Software, and to permit persons to whom the Software is 9 // furnished to do so, subject to the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included in 12 // all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 // THE SOFTWARE. 21 22 module capnproto.SegmentBuilder; 23 24 import java.nio.ByteBuffer; 25 26 import capnproto.Arena; 27 import capnproto.BuilderArena; 28 import capnproto.Constants; 29 import capnproto.SegmentReader; 30 31 struct SegmentBuilder 32 { 33 public: //Variables. 34 static int FAILED_ALLOCATION = -1; 35 36 size_t pos = 0; //In words. 37 int id = 0; 38 39 public: //Methods. 40 this(ByteBuffer buf, Arena arena) 41 { 42 reader = SegmentReader(buf, arena); 43 } 44 45 ///Returns how many words have already been allocated. 46 size_t currentSize() const 47 { 48 return this.pos; 49 } 50 51 ///Allocate `amount` words. 52 size_t allocate(size_t amount) 53 { 54 assert(amount >= 0, "Tried to allocate a negative number of words."); 55 if(amount > this.capacity() - this.pos) 56 return FAILED_ALLOCATION; //No space left. 57 scope(exit) this.pos += amount; 58 return this.pos; 59 } 60 61 BuilderArena getArena() 62 { 63 return cast(BuilderArena)reader.arena; 64 } 65 66 bool isWritable() const 67 { 68 //TODO: Support external non-writable segments. 69 return true; 70 } 71 72 void put(int index, long value) 73 { 74 buffer.put!long(index * Constants.BYTES_PER_WORD, value); 75 } 76 77 SegmentReader* asReader() 78 { 79 return &reader; 80 } 81 82 alias reader this; 83 84 package: //Variables. 85 SegmentReader reader; 86 87 private: //Methods. 88 ///The total number of words the buffer can hold. 89 size_t capacity() 90 { 91 this.buffer.rewind(); 92 return this.buffer.remaining() / 8; 93 } 94 }