91803d68138435399a4b02fd49e2f527dde86a45.svn-base 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. package io.agora.media;
  2. import java.nio.ByteBuffer;
  3. import java.nio.ByteOrder;
  4. import java.util.Map;
  5. import java.util.TreeMap;
  6. /**
  7. * Created by Li on 10/1/2016.
  8. */
  9. public class ByteBuf {
  10. ByteBuffer buffer = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN);
  11. public ByteBuf() {
  12. }
  13. public ByteBuf(byte[] bytes) {
  14. this.buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
  15. }
  16. public byte[] asBytes() {
  17. byte[] out = new byte[buffer.position()];
  18. buffer.rewind();
  19. buffer.get(out, 0, out.length);
  20. return out;
  21. }
  22. // packUint16
  23. public ByteBuf put(short v) {
  24. buffer.putShort(v);
  25. return this;
  26. }
  27. public ByteBuf put(byte[] v) {
  28. put((short)v.length);
  29. buffer.put(v);
  30. return this;
  31. }
  32. // packUint32
  33. public ByteBuf put(int v) {
  34. buffer.putInt(v);
  35. return this;
  36. }
  37. public ByteBuf put(long v) {
  38. buffer.putLong(v);
  39. return this;
  40. }
  41. public ByteBuf put(String v) {
  42. return put(v.getBytes());
  43. }
  44. public ByteBuf put(TreeMap<Short, String> extra) {
  45. put((short)extra.size());
  46. for (Map.Entry<Short, String> pair : extra.entrySet()) {
  47. put(pair.getKey());
  48. put(pair.getValue());
  49. }
  50. return this;
  51. }
  52. public ByteBuf putIntMap(TreeMap<Short, Integer> extra) {
  53. put((short)extra.size());
  54. for (Map.Entry<Short, Integer> pair : extra.entrySet()) {
  55. put(pair.getKey());
  56. put(pair.getValue());
  57. }
  58. return this;
  59. }
  60. public short readShort() {
  61. return buffer.getShort();
  62. }
  63. public int readInt() {
  64. return buffer.getInt();
  65. }
  66. public byte[] readBytes() {
  67. short length = readShort();
  68. byte[] bytes = new byte[length];
  69. buffer.get(bytes);
  70. return bytes;
  71. }
  72. public String readString() {
  73. byte[] bytes = readBytes();
  74. return new String(bytes);
  75. }
  76. public TreeMap<Short, String> readMap() {
  77. TreeMap<Short, String> map = new TreeMap<>();
  78. short length = readShort();
  79. for (short i = 0; i < length; ++i) {
  80. short k = readShort();
  81. String v = readString();
  82. map.put(k, v);
  83. }
  84. return map;
  85. }
  86. public TreeMap<Short, Integer> readIntMap() {
  87. TreeMap<Short, Integer> map = new TreeMap<>();
  88. short length = readShort();
  89. for (short i = 0; i < length; ++i) {
  90. short k = readShort();
  91. Integer v = readInt();
  92. map.put(k, v);
  93. }
  94. return map;
  95. }
  96. }