StructBase.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.UnsupportedEncodingException;
  10. import java.util.Date;
  11. /**
  12. * C struct body decoder
  13. *
  14. * @author Happy Fish / YuQing
  15. * @version Version 1.17
  16. */
  17. public abstract class StructBase {
  18. /**
  19. * set fields
  20. *
  21. * @param bs byte array
  22. * @param offset start offset
  23. */
  24. public abstract void setFields(byte[] bs, int offset);
  25. protected String stringValue(byte[] bs, int offset, FieldInfo filedInfo) {
  26. try {
  27. return (new String(bs, offset + filedInfo.offset, filedInfo.size, ClientGlobal.g_charset)).trim();
  28. } catch (UnsupportedEncodingException ex) {
  29. ex.printStackTrace();
  30. return null;
  31. }
  32. }
  33. protected long longValue(byte[] bs, int offset, FieldInfo filedInfo) {
  34. return ProtoCommon.buff2long(bs, offset + filedInfo.offset);
  35. }
  36. protected int intValue(byte[] bs, int offset, FieldInfo filedInfo) {
  37. return (int) ProtoCommon.buff2long(bs, offset + filedInfo.offset);
  38. }
  39. protected int int32Value(byte[] bs, int offset, FieldInfo filedInfo) {
  40. return ProtoCommon.buff2int(bs, offset + filedInfo.offset);
  41. }
  42. protected byte byteValue(byte[] bs, int offset, FieldInfo filedInfo) {
  43. return bs[offset + filedInfo.offset];
  44. }
  45. protected boolean booleanValue(byte[] bs, int offset, FieldInfo filedInfo) {
  46. return bs[offset + filedInfo.offset] != 0;
  47. }
  48. protected Date dateValue(byte[] bs, int offset, FieldInfo filedInfo) {
  49. return new Date(ProtoCommon.buff2long(bs, offset + filedInfo.offset) * 1000);
  50. }
  51. protected static class FieldInfo {
  52. protected String name;
  53. protected int offset;
  54. protected int size;
  55. public FieldInfo(String name, int offset, int size) {
  56. this.name = name;
  57. this.offset = offset;
  58. this.size = size;
  59. }
  60. }
  61. }