1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.internal.objects;
  27 
  28 import static jdk.nashorn.internal.codegen.CompilerConstants.specialCall;
  29 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
  30 import static jdk.nashorn.internal.lookup.Lookup.MH;
  31 
  32 import java.lang.invoke.MethodHandle;
  33 import java.lang.invoke.MethodHandles;
  34 import java.nio.ByteBuffer;
  35 import jdk.nashorn.internal.objects.annotations.Attribute;
  36 import jdk.nashorn.internal.objects.annotations.Constructor;
  37 import jdk.nashorn.internal.objects.annotations.Function;
  38 import jdk.nashorn.internal.objects.annotations.Property;
  39 import jdk.nashorn.internal.objects.annotations.ScriptClass;
  40 import jdk.nashorn.internal.objects.annotations.Where;
  41 import jdk.nashorn.internal.runtime.JSType;
  42 import jdk.nashorn.internal.runtime.PropertyMap;
  43 import jdk.nashorn.internal.runtime.ScriptObject;
  44 import jdk.nashorn.internal.runtime.arrays.ArrayData;
  45 import jdk.nashorn.internal.runtime.arrays.TypedArrayData;
  46 
  47 /**
  48  * Uint8 clamped array for TypedArray extension
  49  */
  50 @ScriptClass("Uint8ClampedArray")
  51 public final class NativeUint8ClampedArray extends ArrayBufferView {
  52     /**
  53      * The size in bytes of each element in the array.
  54      */
  55     @Property(attributes = Attribute.NOT_ENUMERABLE | Attribute.NOT_WRITABLE | Attribute.NOT_CONFIGURABLE, where = Where.CONSTRUCTOR)
  56     public static final int BYTES_PER_ELEMENT = 1;
  57 
  58     // initialized by nasgen
  59     @SuppressWarnings("unused")
  60     private static PropertyMap $nasgenmap$;
  61 
  62     private static final Factory FACTORY = new Factory(BYTES_PER_ELEMENT) {
  63         @Override
  64         public ArrayBufferView construct(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
  65             return new NativeUint8ClampedArray(buffer, byteOffset, length);
  66         }
  67 
  68         @Override
  69         public Uint8ClampedArrayData createArrayData(final ByteBuffer nb, final int start, final int end) {
  70             return new Uint8ClampedArrayData(nb, start, end);
  71         }
  72 
  73         @Override
  74         public String getClassName() {
  75             return "Uint8ClampedArray";
  76         }
  77     };
  78 
  79     private static final class Uint8ClampedArrayData extends TypedArrayData<ByteBuffer> {
  80 
  81         private static final MethodHandle GET_ELEM = specialCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "getElem", int.class, int.class).methodHandle();
  82         private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "setElem", void.class, int.class, int.class).methodHandle();
  83         private static final MethodHandle RINT_D   = staticCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "rint", double.class, double.class).methodHandle();
  84         private static final MethodHandle RINT_O   = staticCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "rint", Object.class, Object.class).methodHandle();
  85         private static final MethodHandle CLAMP_LONG = staticCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "clampLong", long.class, long.class).methodHandle();
  86 
  87         private Uint8ClampedArrayData(final ByteBuffer nb, final int start, final int end) {
  88             super(((ByteBuffer)nb.position(start).limit(end)).slice(), end - start);
  89         }
  90 
  91         @Override
  92         protected MethodHandle getGetElem() {
  93             return GET_ELEM;
  94         }
  95 
  96         @Override
  97         protected MethodHandle getSetElem() {
  98             return SET_ELEM;
  99         }
 100 
 101         @Override
 102         public Class<?> getElementType() {
 103             return int.class;
 104         }
 105 
 106         @Override
 107         public Class<?> getBoxedElementType() {
 108             return int.class;
 109         }
 110 
 111         private int getElem(final int index) {
 112             try {
 113                 return nb.get(index) & 0xff;
 114             } catch (final IndexOutOfBoundsException e) {
 115                 throw new ClassCastException(); //force relink - this works for unoptimistic too
 116             }
 117         }
 118 
 119         @Override
 120         public MethodHandle getElementSetter(final Class<?> elementType) {
 121             final MethodHandle setter = super.getElementSetter(elementType); //getContinuousElementSetter(getClass(), setElem(), elementType);
 122             if (setter != null) {
 123                 if (elementType == Object.class) {
 124                     return MH.filterArguments(setter, 2, RINT_O);
 125                 } else if (elementType == double.class) {
 126                     return MH.filterArguments(setter, 2, RINT_D);
 127                 } else if (elementType == long.class) {
 128                     return MH.filterArguments(setter, 2, CLAMP_LONG);
 129                 }
 130             }
 131             return setter;
 132         }
 133 
 134         private void setElem(final int index, final int elem) {
 135             try {
 136                 if (index < nb.limit()) {
 137                     final byte clamped;
 138                     if ((elem & 0xffff_ff00) == 0) {
 139                         clamped = (byte) elem;
 140                     } else {
 141                         clamped = elem < 0 ? 0 : (byte) 0xff;
 142                     }
 143                     nb.put(index, clamped);
 144                 }
 145             } catch (final IndexOutOfBoundsException e) {
 146                 throw new ClassCastException();
 147             }
 148         }
 149 
 150         @Override
 151         public boolean isClamped() {
 152             return true;
 153         }
 154 
 155         @Override
 156         public boolean isUnsigned() {
 157             return true;
 158         }
 159 
 160         @Override
 161         public int getInt(final int index) {
 162             return getElem(index);
 163         }
 164 
 165         @Override
 166         public int getIntOptimistic(final int index, final int programPoint) {
 167             return getElem(index);
 168         }
 169 
 170         @Override
 171         public long getLong(final int index) {
 172             return getInt(index);
 173         }
 174 
 175         @Override
 176         public long getLongOptimistic(final int index, final int programPoint) {
 177             return getElem(index);
 178         }
 179 
 180         @Override
 181         public double getDouble(final int index) {
 182             return getInt(index);
 183         }
 184 
 185         @Override
 186         public double getDoubleOptimistic(final int index, final int programPoint) {
 187             return getElem(index);
 188         }
 189 
 190         @Override
 191         public Object getObject(final int index) {
 192             return getInt(index);
 193         }
 194 
 195         @Override
 196         public ArrayData set(final int index, final Object value, final boolean strict) {
 197             return set(index, JSType.toNumber(value), strict);
 198         }
 199 
 200         @Override
 201         public ArrayData set(final int index, final int value, final boolean strict) {
 202             setElem(index, value);
 203             return this;
 204         }
 205 
 206         @Override
 207         public ArrayData set(final int index, final long value, final boolean strict) {
 208             return set(index, (int)value, strict);
 209         }
 210 
 211         @Override
 212         public ArrayData set(final int index, final double value, final boolean strict) {
 213             return set(index, rint(value), strict);
 214         }
 215 
 216         private static double rint(final double rint) {
 217             return (int)Math.rint(rint);
 218         }
 219 
 220         @SuppressWarnings("unused")
 221         private static Object rint(final Object rint) {
 222             return rint(JSType.toNumber(rint));
 223         }
 224 
 225         @SuppressWarnings("unused")
 226         private static long clampLong(final long l) {
 227             if(l < 0L) {
 228                 return 0L;
 229             } else if(l > 0xffL) {
 230                 return 0xffL;
 231             }
 232             return l;
 233         }
 234     }
 235 
 236     /**
 237      * Constructor
 238      *
 239      * @param newObj is this typed array instantiated with the new operator
 240      * @param self   self reference
 241      * @param args   args
 242      *
 243      * @return new typed array
 244      */
 245     @Constructor(arity = 1)
 246     public static NativeUint8ClampedArray constructor(final boolean newObj, final Object self, final Object... args) {
 247         return (NativeUint8ClampedArray)constructorImpl(newObj, args, FACTORY);
 248     }
 249 
 250     NativeUint8ClampedArray(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
 251         super(buffer, byteOffset, length);
 252     }
 253 
 254     @Override
 255     protected Factory factory() {
 256         return FACTORY;
 257     }
 258 
 259     /**
 260      * Set values
 261      * @param self   self reference
 262      * @param array  multiple values of array's type to set
 263      * @param offset optional start index, interpreted  0 if undefined
 264      * @return undefined
 265      */
 266     @Function(attributes = Attribute.NOT_ENUMERABLE)
 267     protected static Object set(final Object self, final Object array, final Object offset) {
 268         return ArrayBufferView.setImpl(self, array, offset);
 269     }
 270 
 271     /**
 272      * Returns a new TypedArray view of the ArrayBuffer store for this TypedArray,
 273      * referencing the elements at begin, inclusive, up to end, exclusive. If either
 274      * begin or end is negative, it refers to an index from the end of the array,
 275      * as opposed to from the beginning.
 276      * <p>
 277      * If end is unspecified, the subarray contains all elements from begin to the end
 278      * of the TypedArray. The range specified by the begin and end values is clamped to
 279      * the valid index range for the current array. If the computed length of the new
 280      * TypedArray would be negative, it is clamped to zero.
 281      * <p>
 282      * The returned TypedArray will be of the same type as the array on which this
 283      * method is invoked.
 284      *
 285      * @param self self reference
 286      * @param begin begin position
 287      * @param end end position
 288      *
 289      * @return sub array
 290      */
 291     @Function(attributes = Attribute.NOT_ENUMERABLE)
 292     protected static NativeUint8ClampedArray subarray(final Object self, final Object begin, final Object end) {
 293         return (NativeUint8ClampedArray)ArrayBufferView.subarrayImpl(self, begin, end);
 294     }
 295 
 296     @Override
 297     protected ScriptObject getPrototype(final Global global) {
 298         return global.getUint8ClampedArrayPrototype();
 299     }
 300 }