Esempio n. 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();
  }
Esempio n. 2
0
  @JRubyMethod(compat = RUBY1_9, meta = true)
  public static IRubyObject asciicompat_encoding(
      ThreadContext context, IRubyObject self, IRubyObject strOrEnc) {
    Ruby runtime = context.runtime;
    EncodingService encodingService = runtime.getEncodingService();

    Encoding encoding = encodingService.getEncodingFromObjectNoError(strOrEnc);

    if (encoding == null) {
      return context.nil;
    }

    if (encoding.isAsciiCompatible()) {
      return context.nil;
    }

    Encoding asciiCompat = NONASCII_TO_ASCII.get(encoding);

    if (asciiCompat == null) {
      throw runtime.newConverterNotFoundError("no ASCII compatible encoding found for " + strOrEnc);
    }

    return encodingService.convertEncodingToRubyEncoding(asciiCompat);
  }