Dean Hiller
Dean Hiller

Reputation: 20200

Data structure for write/read bytes

I keep running into the case where I want some structure of let's say buffer size 4096 and I can

  1. write bytes into
  2. read bytes from it
  3. reset the read back to the previous read
  4. MOST IMPORTANT, not have to deal with copying stuff as data windows get near the end of the byte array!!! (This is much like a circular buffer basically with wrap around or something)

ByteBuffer seems just as much of a heartache as byte[] as you write to it and read from it on both of these, the beginning of the array starts to empty out. I almost just want a structure of List or something....I just want it all managed for me (or I may have to write my own structure). I think some kind of InputStream would be nice with a mark and reset so I can mark before I read and then reset in case there is not enough data in the buffer just yet.

This is extremely useful in nearly all asynchronous programming where data comes in and you may have enough to parse or may not have enough to parse and you fill the buffer, try to read and parse and need to reset until you have more data.

Upvotes: 2

Views: 261

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198163

ByteBuffer seems totally right for this, and ByteBuffer.compact() is really what you want to use when you want to move the remaining buffer back to the start.

Upvotes: 2

Dean Hiller
Dean Hiller

Reputation: 20200

hmmm, I just found this non-GPL one...apache license looks like..

https://svn.apache.org/repos/asf/etch/releases/release-1.0.0/util/src/main/java/etch/util/CircularByteBuffer.java

anyone use this? lloks ok to me.

Upvotes: 0

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

You might be able to use this circular byte buffer - use the getAvailable() method rather than reading and then resetting.

Upvotes: 0

Related Questions