示例#1
0
  @JRubyMethod(visibility = PRIVATE)
  public IRubyObject initialize(
      ThreadContext context, IRubyObject src, IRubyObject dest, IRubyObject _opt) {
    Ruby runtime = context.runtime;
    EncodingService encodingService = runtime.getEncodingService();

    // both may be null
    Encoding srcEncoding = encodingService.getEncodingFromObjectNoError(src);
    Encoding destEncoding = encodingService.getEncodingFromObjectNoError(dest);

    int flags = 0;
    IRubyObject replace = context.nil;

    if (srcEncoding == destEncoding && srcEncoding != null) {
      throw runtime.newConverterNotFoundError(
          "code converter not found (" + srcEncoding + " to " + destEncoding + ")");
    }

    // Ensure we'll be able to get charsets fo these encodings
    try {
      if (srcEncoding != destEncoding) {
        if (srcEncoding != null) encodingService.charsetForEncoding(srcEncoding);
        if (destEncoding != null) encodingService.charsetForEncoding(destEncoding);
      }
    } catch (RaiseException e) {
      if (e.getException().getMetaClass().getBaseName().equals("CompatibilityError")) {
        throw runtime.newConverterNotFoundError(
            "code converter not found (" + srcEncoding + " to " + destEncoding + ")");
      } else {
        throw e;
      }
    }

    if (!_opt.isNil()) {
      if (_opt instanceof RubyHash) {
        RubyHash opt = (RubyHash) _opt;
        flags |= EncodingUtils.econvPrepareOpts(context, opt, new IRubyObject[] {opt});

        IRubyObject value = opt.fastARef(runtime.newSymbol("replace"));
        if (value != null) {
          replace = value;
        }
      } else {
        flags = (int) _opt.convertToInteger().getLongValue();
        replace = context.nil;
      }
    }

    transcoder = new CharsetTranscoder(context, destEncoding, srcEncoding, flags, replace);

    return context.runtime.getNil();
  }