1 jls.loader.provide('jls.io.BufferChannel'); 2 3 jls.loader.require('jls.lang.ByteBuffer'); 4 5 /** 6 * @namespace Provides for system input and output through data streams, serialization and the file system. 7 * @name jls.io 8 */ 9 10 jls.io.BufferChannel = jls.lang.Class.create({ 11 initialize : function(buffer) { 12 if (buffer) { 13 if (! (buffer instanceof jls.lang.ByteBuffer)) { 14 throw new jls.lang.Exception('Invalid Buffer argument type (' + (typeof buffer) + ')'); 15 } 16 this._buffer = buffer.slice(); 17 this._append = false; 18 } else { 19 this._buffer = jls.lang.ByteBuffer.allocate(1024); 20 // TODO Use append 21 this._append = true; 22 } 23 }, 24 buffer : function() { 25 return this._buffer; 26 }, 27 close : function() { 28 this._buffer.free(); 29 return this; 30 }, 31 flush : function() { 32 return this; 33 }, 34 readByte : function() { 35 if (this._buffer.remaining() < 1) { 36 return -1; 37 } 38 return this._buffer.getByte(); 39 }, 40 writeByte : function(b) { 41 if (this._buffer.remaining() < 1) { 42 return false; 43 } 44 this._buffer.putByte(b); 45 return true; 46 }, 47 read : function(buffer) { 48 var count = buffer.remaining(); 49 if (count > this._buffer.remaining()) { 50 count = this._buffer.remaining(); 51 } 52 //jls.logger.trace('BufferChannel.read(' + this._buffer.remaining() + '), count: ' + count); 53 if (count > 0) { 54 buffer.putBuffer(this._buffer, count); 55 } 56 return count; 57 }, 58 write : function(buffer) { 59 var count = this._buffer.remaining(); 60 if (count > buffer.remaining()) { 61 count = buffer.remaining(); 62 } 63 //jls.logger.trace('BufferChannel.write(' + this._buffer.remaining() + '), count: ' + count); 64 if (count > 0) { 65 this._buffer.putBuffer(buffer, count); 66 } 67 return count; 68 }, 69 toString : function(csn) { 70 var l = this._buffer.limit(); 71 var p = this._buffer.position(); 72 this._buffer.flip(); 73 var s = this._buffer.getString(csn); 74 this._buffer.setLimit(l); 75 this._buffer.setPosition(p); 76 return s; 77 } 78 }); 79