2 * This code is copyrighted work by Daniel Luz <dev at mernen dot com>.
4 * Distributed under the Ruby and GPLv2 licenses; see COPYING and GPL files
10 import org.jruby.RubyArray;
11 import org.jruby.RubyClass;
12 import org.jruby.RubyException;
13 import org.jruby.RubyHash;
14 import org.jruby.RubyString;
15 import org.jruby.exceptions.RaiseException;
16 import org.jruby.runtime.Block;
17 import org.jruby.runtime.ThreadContext;
18 import org.jruby.runtime.builtin.IRubyObject;
19 import org.jruby.util.ByteList;
22 * Library of miscellaneous utility functions
25 public static final String M_GENERATOR_ERROR = "GeneratorError";
26 public static final String M_NESTING_ERROR = "NestingError";
27 public static final String M_PARSER_ERROR = "ParserError";
30 throw new RuntimeException();
34 * Safe {@link RubyArray} type-checking.
35 * Returns the given object if it is an <code>Array</code>,
36 * or throws an exception if not.
37 * @param object The object to test
38 * @return The given object if it is an <code>Array</code>
39 * @throws RaiseException <code>TypeError</code> if the object is not
40 * of the expected type
42 static RubyArray ensureArray(IRubyObject object) throws RaiseException {
43 if (object instanceof RubyArray) return (RubyArray)object;
44 Ruby runtime = object.getRuntime();
45 throw runtime.newTypeError(object, runtime.getArray());
48 static RubyHash ensureHash(IRubyObject object) throws RaiseException {
49 if (object instanceof RubyHash) return (RubyHash)object;
50 Ruby runtime = object.getRuntime();
51 throw runtime.newTypeError(object, runtime.getHash());
54 static RubyString ensureString(IRubyObject object) throws RaiseException {
55 if (object instanceof RubyString) return (RubyString)object;
56 Ruby runtime = object.getRuntime();
57 throw runtime.newTypeError(object, runtime.getString());
60 static RaiseException newException(ThreadContext context,
61 String className, String message) {
62 return newException(context, className,
63 context.getRuntime().newString(message));
66 static RaiseException newException(ThreadContext context,
67 String className, RubyString message) {
68 RuntimeInfo info = RuntimeInfo.forRuntime(context.getRuntime());
69 RubyClass klazz = info.jsonModule.get().getClass(className);
70 RubyException excptn =
71 (RubyException)klazz.newInstance(context,
72 new IRubyObject[] {message}, Block.NULL_BLOCK);
73 return new RaiseException(excptn);
76 static byte[] repeat(ByteList a, int n) {
77 return repeat(a.unsafeBytes(), a.begin(), a.length(), n);
80 static byte[] repeat(byte[] a, int begin, int length, int n) {
81 if (length == 0) return ByteList.NULL_ARRAY;
82 int resultLen = length * n;
83 byte[] result = new byte[resultLen];
84 for (int pos = 0; pos < resultLen; pos += length) {
85 System.arraycopy(a, begin, result, pos, length);