javap/src/main/java/org/apidesign/javap/Vector.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 13 Dec 2012 23:20:47 +0100
changeset 316 8da329789435
parent 167 77f7135b6eb1
child 376 059cb07ac9b3
permissions -rw-r--r--
Providing JavaScript specific implementations of Hashtable and Vector. Those should likely be faster for the JavaScript VM than interpreting bytecode. This is the way to get the best of JavaScript and yet provide reasonably well working implementation in Java.
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 package org.apidesign.javap;
     6 
     7 import org.apidesign.bck2brwsr.core.JavaScriptBody;
     8 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
     9 
    10 /** A JavaScript ready replacement for java.util.Vector
    11  *
    12  * @author Jaroslav Tulach <jtulach@netbeans.org>
    13  */
    14 @JavaScriptPrototype(prototype = "new Array" )
    15 final class Vector {
    16     private Object[] arr;
    17     
    18     Vector() {
    19     }
    20 
    21     Vector(int i) {
    22     }
    23 
    24     void add(Object objectType) {
    25         addElement(objectType);
    26     }
    27     @JavaScriptBody(args = { "self", "obj" }, body = 
    28         "self.push(obj);"
    29     )
    30     void addElement(Object obj) {
    31         final int s = size();
    32         setSize(s + 1);
    33         setElementAt(obj, s);
    34     }
    35 
    36     @JavaScriptBody(args = { "self" }, body = 
    37         "return self.length;"
    38     )
    39     int size() {
    40         return arr == null ? 0 : arr.length;
    41     }
    42 
    43     @JavaScriptBody(args = { "self", "newArr" }, body =
    44         "for (var i = 0; i < self.length; i++) {\n"
    45       + "  newArr[i] = self[i];\n"
    46       + "}\n")
    47     void copyInto(Object[] newArr) {
    48         if (arr == null) {
    49             return;
    50         }
    51         int min = Math.min(newArr.length, arr.length);
    52         for (int i = 0; i < min; i++) {
    53             newArr[i] = arr[i];
    54         }
    55     }
    56 
    57     @JavaScriptBody(args = { "self", "index" }, body =
    58         "return self[index];"
    59     )
    60     Object elementAt(int index) {
    61         return arr[index];
    62     }
    63 
    64     private void setSize(int len) {
    65         Object[] newArr = new Object[len];
    66         copyInto(newArr);
    67         arr = newArr;
    68     }
    69 
    70     @JavaScriptBody(args = { "self", "val", "index" }, body = 
    71         "self[index] = val;"
    72     )
    73     void setElementAt(Object val, int index) {
    74         arr[index] = val;
    75     }
    76 }