예제 #1
0
  @JRubyMethod
  public IRubyObject convert(ThreadContext context, IRubyObject srcBuffer) {
    if (!(srcBuffer instanceof RubyString)) {
      throw context.runtime.newTypeError(srcBuffer, context.runtime.getString());
    }

    RubyString srcString = (RubyString) srcBuffer;

    ByteList srcBL = srcString.getByteList();

    if (srcBL.getRealSize() == 0) return context.runtime.newSymbol("source_buffer_empty");

    ByteBuffer srcBB = ByteBuffer.wrap(srcBL.getUnsafeBytes(), srcBL.begin(), srcBL.getRealSize());
    try {
      CharBuffer srcCB =
          CharBuffer.allocate((int) (srcDecoder.maxCharsPerByte() * srcBL.getRealSize()) + 1);
      CoderResult decodeResult = srcDecoder.decode(srcBB, srcCB, true);
      srcCB.flip();

      ByteBuffer destBB =
          ByteBuffer.allocate((int) (destEncoder.maxBytesPerChar() * srcCB.limit()) + 1);
      CoderResult encodeResult = destEncoder.encode(srcCB, destBB, true);
      destBB.flip();

      byte[] destBytes = new byte[destBB.limit()];
      destBB.get(destBytes);

      srcDecoder.reset();
      destEncoder.reset();

      return context.runtime.newString(new ByteList(destBytes, destEncoding.getEncoding(), false));
    } catch (Exception e) {
      throw context.runtime.newRuntimeError(e.getLocalizedMessage());
    }
  }
예제 #2
0
  @JRubyMethod(visibility = PRIVATE)
  public IRubyObject initialize(ThreadContext context, IRubyObject src, IRubyObject dest) {

    if (src instanceof RubyEncoding) {
      srcEncoding = (RubyEncoding) src;
    } else {
      srcEncoding = (RubyEncoding) context.runtime.getEncodingService().rubyEncodingFromObject(src);
    }

    if (dest instanceof RubyEncoding) {
      destEncoding = (RubyEncoding) dest;
    } else {
      destEncoding =
          (RubyEncoding) context.runtime.getEncodingService().rubyEncodingFromObject(dest);
    }

    try {
      srcDecoder =
          context
              .runtime
              .getEncodingService()
              .charsetForEncoding(srcEncoding.getEncoding())
              .newDecoder();
      destEncoder =
          context
              .runtime
              .getEncodingService()
              .charsetForEncoding(destEncoding.getEncoding())
              .newEncoder();
    } catch (RaiseException e) {
      if (e.getException().getMetaClass().getBaseName().equals("CompatibilityError")) {
        throw context.runtime.newConverterNotFoundError(
            "code converter not found (" + srcEncoding + " to " + destEncoding + ")");
      } else {
        throw e;
      }
    }

    return context.runtime.getNil();
  }