ProtoStructDecoder.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Copyright (C) 2008 Happy Fish / YuQing
  3. * <p>
  4. * FastDFS Java Client may be copied only under the terms of the GNU Lesser
  5. * General Public License (LGPL).
  6. * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
  7. */
  8. package com.kmall.common.fileserver.fastdfs;
  9. import java.io.IOException;
  10. import java.lang.reflect.Array;
  11. /**
  12. * C struct body decoder
  13. *
  14. * @author Happy Fish / YuQing
  15. * @version Version 1.17
  16. */
  17. public class ProtoStructDecoder<T extends StructBase> {
  18. /**
  19. * Constructor
  20. */
  21. public ProtoStructDecoder() {
  22. }
  23. /**
  24. * decode byte buffer
  25. */
  26. public T[] decode(byte[] bs, Class<T> clazz, int fieldsTotalSize) throws Exception {
  27. if (bs.length % fieldsTotalSize != 0) {
  28. throw new IOException("byte array length: " + bs.length + " is invalid!");
  29. }
  30. int count = bs.length / fieldsTotalSize;
  31. int offset;
  32. T[] results = (T[]) Array.newInstance(clazz, count);
  33. offset = 0;
  34. for (int i = 0; i < results.length; i++) {
  35. results[i] = clazz.newInstance();
  36. results[i].setFields(bs, offset);
  37. offset += fieldsTotalSize;
  38. }
  39. return results;
  40. }
  41. }