コード例 #1
0
ファイル: RubyRange.java プロジェクト: headius/jruby-cdc
  final int[] begLenInt(int len, int err) {
    int beg = RubyNumeric.num2int(this.begin);
    int end = RubyNumeric.num2int(this.end);

    if (beg < 0) {
      beg += len;
      if (beg < 0) {
        if (err != 0)
          throw getRuntime()
              .newRangeError(beg + ".." + (isExclusive ? "." : "") + end + " out of range");
        return null;
      }
    }

    if (err == 0 || err == 2) {
      if (beg > len) {
        if (err != 0)
          throw getRuntime()
              .newRangeError(beg + ".." + (isExclusive ? "." : "") + end + " out of range");
        return null;
      }
      if (end > len) end = len;
    }

    if (end < 0) end += len;
    if (!isExclusive) end++;
    len = end - beg;
    if (len < 0) len = 0;

    return new int[] {beg, len};
  }
コード例 #2
0
ファイル: StringIO.java プロジェクト: Jared-Prime/jruby
  @JRubyMethod(required = 1, optional = 1)
  public IRubyObject seek(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;

    checkFrozen();
    checkFinalized();

    int offset = RubyNumeric.num2int(args[0]);
    IRubyObject whence = context.nil;

    if (args.length > 1 && !args[0].isNil()) whence = args[1];

    checkOpen();

    switch (whence.isNil() ? 0 : RubyNumeric.num2int(whence)) {
      case 0:
        break;
      case 1:
        offset += ptr.pos;
        break;
      case 2:
        offset += ptr.string.size();
        break;
      default:
        throw runtime.newErrnoEINVALError("invalid whence");
    }

    if (offset < 0) throw runtime.newErrnoEINVALError("invalid seek value");

    ptr.pos = offset;

    return RubyFixnum.zero(runtime);
  }
コード例 #3
0
ファイル: RubyInteger.java プロジェクト: techwhizbang/jruby
  @JRubyMethod(name = "round", compat = CompatVersion.RUBY1_9)
  public IRubyObject round19(ThreadContext context, IRubyObject arg) {
    int ndigits = RubyNumeric.num2int(arg);
    if (ndigits > 0) return RubyKernel.new_float(this, this);
    if (ndigits == 0) return this;
    ndigits = -ndigits;
    Ruby runtime = context.getRuntime();
    if (ndigits < 0) throw runtime.newArgumentError("ndigits out of range");
    IRubyObject f = Numeric.int_pow(context, 10, ndigits);

    if (this instanceof RubyFixnum && f instanceof RubyFixnum) {
      long x = ((RubyFixnum) this).getLongValue();
      long y = ((RubyFixnum) f).getLongValue();
      boolean neg = x < 0;
      if (neg) x = -x;
      x = (x + y / 2) / y * y;
      if (neg) x = -x;
      return RubyFixnum.newFixnum(runtime, x);
    } else {
      IRubyObject h = f.callMethod(context, "/", RubyFixnum.two(runtime));
      IRubyObject r = callMethod(context, "%", f);
      IRubyObject n = callMethod(context, "-", r);
      if (!r.callMethod(context, "<", h).isTrue()) n = n.callMethod(context, "+", f);
      return n;
    }
  }
コード例 #4
0
ファイル: RubyMatchData.java プロジェクト: lopex/jruby
 /** match_end */
 @JRubyMethod(name = "end", compat = CompatVersion.RUBY1_8)
 public IRubyObject end(ThreadContext context, IRubyObject index) {
   int i = RubyNumeric.num2int(index);
   Ruby runtime = context.getRuntime();
   int e = endCommon(runtime, i);
   return e < 0 ? runtime.getNil() : RubyFixnum.newFixnum(runtime, e);
 }
コード例 #5
0
ファイル: RubyInteger.java プロジェクト: bruceadams/jruby
  @JRubyMethod(name = "round", compat = CompatVersion.RUBY1_9)
  public IRubyObject round19(ThreadContext context, IRubyObject arg) {
    int ndigits = RubyNumeric.num2int(arg);
    if (ndigits > 0) return RubyKernel.new_float(this, this);
    if (ndigits == 0) return this;
    Ruby runtime = context.runtime;

    long bytes = (this instanceof RubyFixnum) ? 8 : RubyFixnum.fix2long(callMethod("size"));
    /* If 10**N/2 > this, return 0 */
    /* We have log_256(10) > 0.415241 and log_256(1/2)=-0.125 */
    if (-0.415241 * ndigits - 0.125 > bytes) {
      return RubyFixnum.zero(runtime);
    }

    IRubyObject f = Numeric.int_pow(context, 10, -ndigits);

    if (this instanceof RubyFixnum && f instanceof RubyFixnum) {
      long x = ((RubyFixnum) this).getLongValue();
      long y = ((RubyFixnum) f).getLongValue();
      boolean neg = x < 0;
      if (neg) x = -x;
      x = (x + y / 2) / y * y;
      if (neg) x = -x;
      return RubyFixnum.newFixnum(runtime, x);
    } else if (f instanceof RubyFloat) {
      return RubyFixnum.zero(runtime);
    } else {
      IRubyObject h = f.callMethod(context, "/", RubyFixnum.two(runtime));
      IRubyObject r = callMethod(context, "%", f);
      IRubyObject n = callMethod(context, "-", r);
      String op = callMethod(context, "<", RubyFixnum.zero(runtime)).isTrue() ? "<=" : "<";
      if (!r.callMethod(context, op, h).isTrue()) n = n.callMethod(context, "+", f);
      return n;
    }
  }
コード例 #6
0
ファイル: StructLayout.java プロジェクト: techwhizbang/jruby
  @JRubyMethod(name = "new", meta = true, required = 3, optional = 1)
  public static final IRubyObject newStructLayout(
      ThreadContext context, IRubyObject klass, IRubyObject[] args) {

    IRubyObject rbFields = args[0], size = args[1], alignment = args[2];

    if (!(rbFields instanceof RubyArray)) {
      throw context.getRuntime().newTypeError(rbFields, context.getRuntime().getArray());
    }

    List<IRubyObject> fields = Arrays.asList(((RubyArray) rbFields).toJavaArrayMaybeUnsafe());

    return new StructLayout(
        context.getRuntime(),
        (RubyClass) klass,
        fields,
        RubyNumeric.num2int(size),
        RubyNumeric.num2int(alignment));
  }
コード例 #7
0
ファイル: RubyMatchData.java プロジェクト: lopex/jruby
 public final int backrefNumber(IRubyObject obj) {
   check();
   if (obj instanceof RubySymbol) {
     return nameToBackrefNumber((RubyString) ((RubySymbol) obj).id2name());
   } else if (obj instanceof RubyString) {
     return nameToBackrefNumber((RubyString) obj);
   } else {
     return RubyNumeric.num2int(obj);
   }
 }
コード例 #8
0
  @JRubyMethod(name = "ungetc", required = 1)
  @Override
  public IRubyObject ungetc(IRubyObject arg) {
    checkReadable();

    int c = RubyNumeric.num2int(arg);
    if (data.pos == 0) return getRuntime().getNil();
    ungetcCommon(c);
    return getRuntime().getNil();
  }
コード例 #9
0
ファイル: Buffer.java プロジェクト: jlieske/jruby
 @JRubyMethod(name = "[]")
 public final IRubyObject slice(ThreadContext context, IRubyObject indexArg) {
   final int index = RubyNumeric.num2int(indexArg);
   final int offset = index * typeSize;
   if (offset >= size) {
     throw context.getRuntime().newIndexError(String.format("Index %d out of range", index));
   }
   return new Buffer(
       context.getRuntime(),
       getMetaClass(),
       io.slice(offset),
       size - offset,
       typeSize,
       this.inout);
 }
コード例 #10
0
ファイル: Readline.java プロジェクト: moses/jruby
    @JRubyMethod(name = "delete_at")
    public static IRubyObject s_hist_delete_at(IRubyObject recv, IRubyObject index) {
      Ruby runtime = recv.getRuntime();
      ThreadContext context = runtime.getCurrentContext();

      ConsoleHolder holder = getHolder(runtime);
      int i = RubyNumeric.num2int(index);

      if (i < 0) i += holder.history.size();

      try {
        return runtime.newString(holder.history.remove(i)).taint(context);
      } catch (IndexOutOfBoundsException ioobe) {
        throw runtime.newIndexError("invalid history index: " + i);
      }
    }
コード例 #11
0
ファイル: RubyRandom.java プロジェクト: graalvm/jrubytruffle
 // c: marshal_load
 @JRubyMethod()
 public IRubyObject marshal_load(ThreadContext context, IRubyObject arg) {
   RubyArray load = arg.convertToArray();
   if (load.size() != 3) {
     throw context.runtime.newArgumentError("wrong dump data");
   }
   if (!(load.eltInternal(0) instanceof RubyBignum)) {
     throw context.runtime.newTypeError(load.eltInternal(0), context.runtime.getBignum());
   }
   RubyBignum state = (RubyBignum) load.eltInternal(0);
   int left = RubyNumeric.num2int(load.eltInternal(1));
   IRubyObject seed = load.eltInternal(2);
   random = new RandomType(seed, state, left);
   if (load.hasVariables()) {
     syncVariables((IRubyObject) load);
   }
   return this;
 }
コード例 #12
0
ファイル: RubyStringIO.java プロジェクト: ribrdb/jruby
  @JRubyMethod(name = "ungetc", required = 1)
  public IRubyObject ungetc(IRubyObject arg) {
    checkReadable();

    int c = RubyNumeric.num2int(arg);
    if (pos == 0) return getRuntime().getNil();
    internal.modify();
    pos--;

    ByteList bytes = internal.getByteList();

    if (bytes.length() <= pos) {
      bytes.length((int) pos + 1);
    }

    bytes.set((int) pos, c);
    return getRuntime().getNil();
  }
コード例 #13
0
ファイル: RubyRandom.java プロジェクト: graalvm/jrubytruffle
 // c: rb_random_bytes
 @JRubyMethod(name = "bytes")
 public IRubyObject bytes(ThreadContext context, IRubyObject arg) {
   int n = RubyNumeric.num2int(arg);
   byte[] bytes = new byte[n];
   int idx = 0;
   for (; n >= 4; n -= 4) {
     int r = random.genrandInt32();
     for (int i = 0; i < 4; ++i) {
       bytes[idx++] = (byte) (r & 0xff);
       r >>>= 8;
     }
   }
   if (n > 0) {
     int r = random.genrandInt32();
     for (int i = 0; i < n; ++i) {
       bytes[idx++] = (byte) (r & 0xff);
       r >>>= 8;
     }
   }
   return context.runtime.newString(new ByteList(bytes));
 }
コード例 #14
0
ファイル: RubyRange.java プロジェクト: headius/jruby-cdc
  @JRubyMethod(name = "first", compat = CompatVersion.RUBY1_9)
  public IRubyObject first(ThreadContext context, IRubyObject arg) {
    final Ruby runtime = context.getRuntime();
    final int num = RubyNumeric.num2int(arg);
    final RubyArray result = runtime.newArray(num);
    try {
      RubyEnumerable.callEach(
          runtime,
          context,
          this,
          new BlockCallback() {
            int n = num;

            public IRubyObject call(ThreadContext ctx, IRubyObject[] largs, Block blk) {
              if (n-- <= 0) throw JumpException.SPECIAL_JUMP;
              result.append(largs[0]);
              return runtime.getNil();
            }
          });
    } catch (JumpException.SpecialJump sj) {
    }
    return result;
  }
コード例 #15
0
ファイル: RubyMatchData.java プロジェクト: lopex/jruby
 /** match_offset */
 @JRubyMethod(name = "offset", compat = CompatVersion.RUBY1_8)
 public IRubyObject offset(ThreadContext context, IRubyObject index) {
   return offsetCommon(context, RubyNumeric.num2int(index), false);
 }
コード例 #16
0
ファイル: SocketUtils.java プロジェクト: trejkaz/jruby
  public static IRubyObject getnameinfo(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    int flags = args.length == 2 ? RubyNumeric.num2int(args[1]) : 0;
    IRubyObject arg0 = args[0];
    String host, port;

    if (arg0 instanceof RubyArray) {
      List list = ((RubyArray) arg0).getList();
      int len = list.size();

      if (len < 3 || len > 4) {
        throw runtime.newArgumentError("array size should be 3 or 4, " + len + " given");
      }

      // if array has 4 elements, third element is ignored
      host = list.size() == 3 ? list.get(2).toString() : list.get(3).toString();
      port = list.get(1).toString();

    } else if (arg0 instanceof RubyString) {
      String arg = ((RubyString) arg0).toString();
      Matcher m = STRING_IPV4_ADDRESS_PATTERN.matcher(arg);

      if (!m.matches()) {
        IRubyObject obj = unpack_sockaddr_in(context, arg0);

        if (obj instanceof RubyArray) {
          List list = ((RubyArray) obj).getList();
          int len = list.size();

          if (len != 2) {
            throw runtime.newArgumentError("invalid address representation");
          }

          host = list.get(1).toString();
          port = list.get(0).toString();

        } else {
          throw runtime.newArgumentError("invalid address string");
        }

      } else if ((host = m.group(IPV4_HOST_GROUP)) == null
          || host.length() == 0
          || (port = m.group(IPV4_PORT_GROUP)) == null
          || port.length() == 0) {

        throw runtime.newArgumentError("invalid address string");

      } else {

        // Try IPv6
        try {
          InetAddress ipv6_addr = InetAddress.getByName(host);

          if (ipv6_addr instanceof Inet6Address) {
            host = ipv6_addr.getHostAddress();
          }

        } catch (UnknownHostException uhe) {
          throw runtime.newArgumentError("invalid address string");
        }
      }

    } else {
      throw runtime.newArgumentError("invalid args");
    }

    InetAddress addr;

    try {
      addr = InetAddress.getByName(host);

    } catch (UnknownHostException e) {
      throw sockerr(runtime, "unknown host: " + host);
    }

    if ((flags & NI_NUMERICHOST.intValue()) == 0) {
      host = addr.getCanonicalHostName();

    } else {
      host = addr.getHostAddress();
    }

    jnr.netdb.Service serv = jnr.netdb.Service.getServiceByPort(Integer.parseInt(port), null);

    if (serv != null) {

      if ((flags & NI_NUMERICSERV.intValue()) == 0) {
        port = serv.getName();

      } else {
        port = Integer.toString(serv.getPort());
      }
    }

    return runtime.newArray(runtime.newString(host), runtime.newString(port));
  }
コード例 #17
0
ファイル: StructLayout.java プロジェクト: techwhizbang/jruby
 void init(IRubyObject name, IRubyObject type, IRubyObject offset) {
   this.name = name;
   this.type = checkType(type);
   this.offset = RubyNumeric.num2int(offset);
 }
コード例 #18
0
ファイル: StringIO.java プロジェクト: Jared-Prime/jruby
  // strio_getline
  private IRubyObject getline(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;

    IRubyObject str = context.nil;
    ;
    int n, limit = -1;

    switch (args.length) {
      case 0:
        str = runtime.getGlobalVariables().get("$/");
        break;

      case 1:
        {
          str = args[0];
          if (!str.isNil() && !(str instanceof RubyString)) {
            IRubyObject tmp = str.checkStringType19();
            if (tmp.isNil()) {
              limit = RubyNumeric.num2int(str);
              if (limit == 0) return runtime.newString();
              str = runtime.getGlobalVariables().get("$/");
            } else {
              str = tmp;
            }
          }
          break;
        }

      case 2:
        if (!args[0].isNil()) str = args[0].convertToString();
        // 2.0 ignores double nil, 1.9 raises
        if (runtime.is2_0()) {
          if (!args[1].isNil()) {
            limit = RubyNumeric.num2int(args[1]);
          }
        } else {
          limit = RubyNumeric.num2int(args[1]);
        }
        break;
    }

    if (isEndOfString()) {
      return context.nil;
    }

    ByteList dataByteList = ptr.string.getByteList();
    byte[] dataBytes = dataByteList.getUnsafeBytes();
    int begin = dataByteList.getBegin();
    int s = begin + ptr.pos;
    int e = begin + dataByteList.getRealSize();
    int p;

    if (limit > 0 && s + limit < e) {
      e = dataByteList.getEncoding().rightAdjustCharHead(dataBytes, s, s + limit, e);
    }
    if (str.isNil()) {
      str = strioSubstr(runtime, ptr.pos, e - s);
    } else if ((n = ((RubyString) str).size()) == 0) {
      // this is not an exact port; the original confused me
      p = s;
      // remove leading \n
      while (dataBytes[p] == '\n') {
        if (++p == e) {
          return context.nil;
        }
      }
      s = p;
      // find next \n or end; if followed by \n, include it too
      p = memchr(dataBytes, p, '\n', e - p);
      if (p != -1) {
        if (++p < e && dataBytes[p] == '\n') {
          e = p + 1;
        } else {
          e = p;
        }
      }
      str = strioSubstr(runtime, s - begin, e - s);
    } else if (n == 1) {
      RubyString strStr = (RubyString) str;
      ByteList strByteList = strStr.getByteList();
      if ((p = memchr(dataBytes, s, strByteList.get(0), e - s)) != -1) {
        e = p + 1;
      }
      str = strioSubstr(runtime, ptr.pos, e - s);
    } else {
      if (n < e - s) {
        RubyString strStr = (RubyString) str;
        ByteList strByteList = strStr.getByteList();
        byte[] strBytes = strByteList.getUnsafeBytes();

        int[] skip = new int[1 << CHAR_BIT];
        int pos;
        p = strByteList.getBegin();
        bm_init_skip(skip, strBytes, p, n);
        if ((pos = bm_search(strBytes, p, n, dataBytes, s, e - s, skip)) >= 0) {
          e = s + pos + n;
        }
      }
      str = strioSubstr(runtime, ptr.pos, e - s);
    }
    ptr.pos = e - begin;
    ptr.lineno++;
    return str;
  }