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 if (count > 0) { 53 buffer.putBuffer(this._buffer, count); 54 } 55 return count; 56 }, 57 write : function(buffer) { 58 var count = this._buffer.remaining(); 59 if (count > buffer.remaining()) { 60 count = buffer.remaining(); 61 } 62 //jls.logger.info('BufferChannel.write(' + this._buffer.remaining() + '), count: ' + count); 63 if (count > 0) { 64 this._buffer.putBuffer(buffer, count); 65 } 66 return count; 67 }, 68 toString : function(csn) { 69 var l = this._buffer.limit(); 70 var p = this._buffer.position(); 71 this._buffer.flip(); 72 var s = this._buffer.getString(csn); 73 this._buffer.setLimit(l); 74 this._buffer.setPosition(p); 75 return s; 76 } 77 }); 78