Beispiel #1
0
  /*
   * Converts unicodes to encoded \uxxxx and writes out any of the
   * characters in specialSaveChars with a preceding slash
   *
   * @param theString
   *            the String needing convert.
   * @param dst
   *            Save of the result
   * @param offset
   *            the offset of result
   * @param escapeSpace
   *            if <code>true</code>, escape Space
   * @param lengthFlag
   *            Whether add one byte of length in the result.
   *            <code>true</code> add one byte of length in the result
   * @param getLengthFlag
   *            Calculate the length of result, if <code>true</code>, theString length that return.
   * @return  if getLengthFlag = false, return offset of the result.
   *          if getLengthFlag = true, the length of the sequence of characters represented by this
   *          object.
   */
  public static int saveConvert(
      String theString,
      byte[] dst,
      int offset,
      boolean escapeSpace,
      boolean lengthFlag,
      boolean getLengthFlag) {
    if (false == getLengthFlag
        && (null == dst
            || dst.length < (offset + (lengthFlag ? 1 : 0))
            || dst.length < 1
            || offset < 0)) {
      return -1;
    }
    if (null == theString) {
      theString = "";
    }
    int length;
    byte[] outBuffer = null;
    if (getLengthFlag) {
      length = UTF8Util.char2ByteUTF8(theString, 0, theString.length(), null, 0, 0, true);
    } else {
      outBuffer = UTF8Util.string2BytesUTF8(theString);
      length = outBuffer.length;
    }

    if (length > 255) {
      length = 255;
    }
    if (getLengthFlag) {
      if (lengthFlag) {
        length = length + 1;
      }
    } else {
      if (dst.length >= offset + length + (lengthFlag ? 1 : 0)) {
        if (lengthFlag) {
          dst[offset] = (byte) (length & 0xFF);
          offset++;
        }
        System.arraycopy(outBuffer, 0, dst, offset, length);
        offset += length;

        length = offset;
      } else {
        length = -1;
      }
    }

    outBuffer = null;

    return length;
  }