PageRenderTime 41ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/alibaba/fastjson/serializer/SerialWriterStringEncoder.java

https://bitbucket.org/xiejuntao/xdesktop
Java | 75 lines | 54 code | 17 blank | 4 comment | 4 complexity | 79cc82892f4d8a4713046eb3e0928424 MD5 | raw file
  1. package com.alibaba.fastjson.serializer;
  2. import java.nio.ByteBuffer;
  3. import java.nio.CharBuffer;
  4. import java.nio.charset.CharacterCodingException;
  5. import java.nio.charset.Charset;
  6. import java.nio.charset.CharsetEncoder;
  7. import java.nio.charset.CoderResult;
  8. import java.nio.charset.CodingErrorAction;
  9. import com.alibaba.fastjson.JSONException;
  10. import com.alibaba.fastjson.util.ThreadLocalCache;
  11. public class SerialWriterStringEncoder {
  12. private final CharsetEncoder encoder;
  13. public SerialWriterStringEncoder(Charset cs) {
  14. this(cs.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE));
  15. }
  16. public SerialWriterStringEncoder(CharsetEncoder encoder) {
  17. this.encoder = encoder;
  18. }
  19. public byte[] encode(char[] chars, int off, int len) {
  20. if (len == 0) {
  21. return new byte[0];
  22. }
  23. encoder.reset();
  24. int bytesLength = scale(len, encoder.maxBytesPerChar());
  25. byte[] bytes = ThreadLocalCache.getBytes(bytesLength);
  26. return encode(chars, off, len, bytes);
  27. }
  28. public CharsetEncoder getEncoder() {
  29. return encoder;
  30. }
  31. public byte[] encode(char[] chars, int off, int len, byte[] bytes) {
  32. ByteBuffer byteBuf = ByteBuffer.wrap(bytes);
  33. CharBuffer charBuf = CharBuffer.wrap(chars, off, len);
  34. try {
  35. CoderResult cr = encoder.encode(charBuf, byteBuf, true);
  36. if (!cr.isUnderflow()) {
  37. cr.throwException();
  38. }
  39. cr = encoder.flush(byteBuf);
  40. if (!cr.isUnderflow()) {
  41. cr.throwException();
  42. }
  43. } catch (CharacterCodingException x) {
  44. // Substitution is always enabled,
  45. // so this shouldn't happen
  46. throw new JSONException(x.getMessage(), x);
  47. }
  48. int bytesLength = byteBuf.position();
  49. byte[] copy = new byte[bytesLength];
  50. System.arraycopy(bytes, 0, copy, 0, bytesLength);
  51. return copy;
  52. }
  53. private static int scale(int len, float expansionFactor) {
  54. // We need to perform double, not float, arithmetic; otherwise
  55. // we lose low order bits when len is larger than 2**24.
  56. return (int) (len * (double) expansionFactor);
  57. }
  58. }