PageRenderTime 57ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/ruby/src/main/java/com/google/protobuf/jruby/Utils.java

https://gitlab.com/yenny.prathivi/protobuf
Java | 303 lines | 234 code | 27 blank | 42 comment | 44 complexity | 94bbb0a20138ca3ea81d7a050130029e MD5 | raw file
  1. /*
  2. * Protocol Buffers - Google's data interchange format
  3. * Copyright 2014 Google Inc. All rights reserved.
  4. * https://developers.google.com/protocol-buffers/
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. package com.google.protobuf.jruby;
  33. import com.google.protobuf.ByteString;
  34. import com.google.protobuf.DescriptorProtos;
  35. import com.google.protobuf.Descriptors;
  36. import org.jcodings.Encoding;
  37. import org.jcodings.specific.ASCIIEncoding;
  38. import org.jcodings.specific.USASCIIEncoding;
  39. import org.jcodings.specific.UTF8Encoding;
  40. import org.jruby.*;
  41. import org.jruby.runtime.Block;
  42. import org.jruby.runtime.ThreadContext;
  43. import org.jruby.runtime.builtin.IRubyObject;
  44. import java.math.BigInteger;
  45. public class Utils {
  46. public static Descriptors.FieldDescriptor.Type rubyToFieldType(IRubyObject typeClass) {
  47. return Descriptors.FieldDescriptor.Type.valueOf(typeClass.asJavaString().toUpperCase());
  48. }
  49. public static IRubyObject fieldTypeToRuby(ThreadContext context, Descriptors.FieldDescriptor.Type type) {
  50. return fieldTypeToRuby(context, type.name());
  51. }
  52. public static IRubyObject fieldTypeToRuby(ThreadContext context, DescriptorProtos.FieldDescriptorProto.Type type) {
  53. return fieldTypeToRuby(context, type.name());
  54. }
  55. private static IRubyObject fieldTypeToRuby(ThreadContext context, String typeName) {
  56. return context.runtime.newSymbol(typeName.replace("TYPE_", "").toLowerCase());
  57. }
  58. public static IRubyObject checkType(ThreadContext context, Descriptors.FieldDescriptor.Type fieldType,
  59. IRubyObject value, RubyModule typeClass) {
  60. Ruby runtime = context.runtime;
  61. Object val;
  62. switch(fieldType) {
  63. case INT32:
  64. case INT64:
  65. case UINT32:
  66. case UINT64:
  67. if (!isRubyNum(value)) {
  68. throw runtime.newTypeError("Expected number type for integral field.");
  69. }
  70. switch(fieldType) {
  71. case INT32:
  72. RubyNumeric.num2int(value);
  73. break;
  74. case INT64:
  75. RubyNumeric.num2long(value);
  76. break;
  77. case UINT32:
  78. num2uint(value);
  79. break;
  80. default:
  81. num2ulong(context.runtime, value);
  82. break;
  83. }
  84. checkIntTypePrecision(context, fieldType, value);
  85. break;
  86. case FLOAT:
  87. if (!isRubyNum(value))
  88. throw runtime.newTypeError("Expected number type for float field.");
  89. break;
  90. case DOUBLE:
  91. if (!isRubyNum(value))
  92. throw runtime.newTypeError("Expected number type for double field.");
  93. break;
  94. case BOOL:
  95. if (!(value instanceof RubyBoolean))
  96. throw runtime.newTypeError("Invalid argument for boolean field.");
  97. break;
  98. case BYTES:
  99. case STRING:
  100. value = validateStringEncoding(context, fieldType, value);
  101. break;
  102. case MESSAGE:
  103. if (value.getMetaClass() != typeClass) {
  104. throw runtime.newTypeError(value, typeClass);
  105. }
  106. break;
  107. case ENUM:
  108. if (value instanceof RubySymbol) {
  109. Descriptors.EnumDescriptor enumDescriptor =
  110. ((RubyEnumDescriptor) typeClass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR)).getDescriptor();
  111. val = enumDescriptor.findValueByName(value.asJavaString());
  112. if (val == null)
  113. throw runtime.newRangeError("Enum value " + value + " is not found.");
  114. } else if(!isRubyNum(value)) {
  115. throw runtime.newTypeError("Expected number or symbol type for enum field.");
  116. }
  117. break;
  118. default:
  119. break;
  120. }
  121. return value;
  122. }
  123. public static IRubyObject wrapPrimaryValue(ThreadContext context, Descriptors.FieldDescriptor.Type fieldType, Object value) {
  124. Ruby runtime = context.runtime;
  125. switch (fieldType) {
  126. case INT32:
  127. return runtime.newFixnum((Integer) value);
  128. case INT64:
  129. return runtime.newFixnum((Long) value);
  130. case UINT32:
  131. return runtime.newFixnum(((Integer) value) & (-1l >>> 32));
  132. case UINT64:
  133. long ret = (Long) value;
  134. return ret >= 0 ? runtime.newFixnum(ret) :
  135. RubyBignum.newBignum(runtime, UINT64_COMPLEMENTARY.add(new BigInteger(ret + "")));
  136. case FLOAT:
  137. return runtime.newFloat((Float) value);
  138. case DOUBLE:
  139. return runtime.newFloat((Double) value);
  140. case BOOL:
  141. return (Boolean) value ? runtime.getTrue() : runtime.getFalse();
  142. case BYTES: {
  143. IRubyObject wrapped = runtime.newString(((ByteString) value).toStringUtf8());
  144. wrapped.setFrozen(true);
  145. return wrapped;
  146. }
  147. case STRING: {
  148. IRubyObject wrapped = runtime.newString(value.toString());
  149. wrapped.setFrozen(true);
  150. return wrapped;
  151. }
  152. default:
  153. return runtime.getNil();
  154. }
  155. }
  156. public static int num2uint(IRubyObject value) {
  157. long longVal = RubyNumeric.num2long(value);
  158. if (longVal > UINT_MAX)
  159. throw value.getRuntime().newRangeError("Integer " + longVal + " too big to convert to 'unsigned int'");
  160. long num = longVal;
  161. if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE)
  162. // encode to UINT32
  163. num = (-longVal ^ (-1l >>> 32) ) + 1;
  164. RubyNumeric.checkInt(value, num);
  165. return (int) num;
  166. }
  167. public static long num2ulong(Ruby runtime, IRubyObject value) {
  168. if (value instanceof RubyFloat) {
  169. RubyBignum bignum = RubyBignum.newBignum(runtime, ((RubyFloat) value).getDoubleValue());
  170. return RubyBignum.big2ulong(bignum);
  171. } else if (value instanceof RubyBignum) {
  172. return RubyBignum.big2ulong((RubyBignum) value);
  173. } else {
  174. return RubyNumeric.num2long(value);
  175. }
  176. }
  177. public static IRubyObject validateStringEncoding(ThreadContext context, Descriptors.FieldDescriptor.Type type, IRubyObject value) {
  178. if (!(value instanceof RubyString))
  179. throw context.runtime.newTypeError("Invalid argument for string field.");
  180. switch(type) {
  181. case BYTES:
  182. value = ((RubyString)value).encode(context, context.runtime.evalScriptlet("Encoding::ASCII_8BIT"));
  183. break;
  184. case STRING:
  185. value = ((RubyString)value).encode(context, context.runtime.evalScriptlet("Encoding::UTF_8"));
  186. break;
  187. default:
  188. break;
  189. }
  190. value.setFrozen(true);
  191. return value;
  192. }
  193. public static void checkNameAvailability(ThreadContext context, String name) {
  194. if (context.runtime.getObject().getConstantAt(name) != null)
  195. throw context.runtime.newNameError(name + " is already defined", name);
  196. }
  197. /**
  198. * Replace invalid "." in descriptor with __DOT__
  199. * @param name
  200. * @return
  201. */
  202. public static String escapeIdentifier(String name) {
  203. return name.replace(".", BADNAME_REPLACEMENT);
  204. }
  205. /**
  206. * Replace __DOT__ in descriptor name with "."
  207. * @param name
  208. * @return
  209. */
  210. public static String unescapeIdentifier(String name) {
  211. return name.replace(BADNAME_REPLACEMENT, ".");
  212. }
  213. public static boolean isMapEntry(Descriptors.FieldDescriptor fieldDescriptor) {
  214. return fieldDescriptor.getType() == Descriptors.FieldDescriptor.Type.MESSAGE &&
  215. fieldDescriptor.isRepeated() &&
  216. fieldDescriptor.getMessageType().getOptions().getMapEntry();
  217. }
  218. public static RubyFieldDescriptor msgdefCreateField(ThreadContext context, String label, IRubyObject name,
  219. IRubyObject type, IRubyObject number, IRubyObject typeClass, RubyClass cFieldDescriptor) {
  220. Ruby runtime = context.runtime;
  221. RubyFieldDescriptor fieldDef = (RubyFieldDescriptor) cFieldDescriptor.newInstance(context, Block.NULL_BLOCK);
  222. fieldDef.setLabel(context, runtime.newString(label));
  223. fieldDef.setName(context, name);
  224. fieldDef.setType(context, type);
  225. fieldDef.setNumber(context, number);
  226. if (!typeClass.isNil()) {
  227. if (!(typeClass instanceof RubyString)) {
  228. throw runtime.newArgumentError("expected string for type class");
  229. }
  230. fieldDef.setSubmsgName(context, typeClass);
  231. }
  232. return fieldDef;
  233. }
  234. protected static void checkIntTypePrecision(ThreadContext context, Descriptors.FieldDescriptor.Type type, IRubyObject value) {
  235. if (value instanceof RubyFloat) {
  236. double doubleVal = RubyNumeric.num2dbl(value);
  237. if (Math.floor(doubleVal) != doubleVal) {
  238. throw context.runtime.newRangeError("Non-integral floating point value assigned to integer field.");
  239. }
  240. }
  241. if (type == Descriptors.FieldDescriptor.Type.UINT32 || type == Descriptors.FieldDescriptor.Type.UINT64) {
  242. if (RubyNumeric.num2dbl(value) < 0) {
  243. throw context.runtime.newRangeError("Assigning negative value to unsigned integer field.");
  244. }
  245. }
  246. }
  247. protected static boolean isRubyNum(Object value) {
  248. return value instanceof RubyFixnum || value instanceof RubyFloat || value instanceof RubyBignum;
  249. }
  250. protected static void validateTypeClass(ThreadContext context, Descriptors.FieldDescriptor.Type type, IRubyObject value) {
  251. Ruby runtime = context.runtime;
  252. if (!(value instanceof RubyModule)) {
  253. throw runtime.newArgumentError("TypeClass has incorrect type");
  254. }
  255. RubyModule klass = (RubyModule) value;
  256. IRubyObject descriptor = klass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR);
  257. if (descriptor.isNil()) {
  258. throw runtime.newArgumentError("Type class has no descriptor. Please pass a " +
  259. "class or enum as returned by the DescriptorPool.");
  260. }
  261. if (type == Descriptors.FieldDescriptor.Type.MESSAGE) {
  262. if (! (descriptor instanceof RubyDescriptor)) {
  263. throw runtime.newArgumentError("Descriptor has an incorrect type");
  264. }
  265. } else if (type == Descriptors.FieldDescriptor.Type.ENUM) {
  266. if (! (descriptor instanceof RubyEnumDescriptor)) {
  267. throw runtime.newArgumentError("Descriptor has an incorrect type");
  268. }
  269. }
  270. }
  271. public static String BADNAME_REPLACEMENT = "__DOT__";
  272. public static String DESCRIPTOR_INSTANCE_VAR = "@descriptor";
  273. public static String EQUAL_SIGN = "=";
  274. private static BigInteger UINT64_COMPLEMENTARY = new BigInteger("18446744073709551616"); //Math.pow(2, 64)
  275. private static long UINT_MAX = 0xffffffffl;
  276. }