NativeUint8ClampedArray.java revision 953:221a84ef44c0
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
26package jdk.nashorn.internal.objects;
27
28import static jdk.nashorn.internal.codegen.CompilerConstants.specialCall;
29import static jdk.nashorn.internal.codegen.CompilerConstants.staticCall;
30import static jdk.nashorn.internal.lookup.Lookup.MH;
31
32import java.lang.invoke.MethodHandle;
33import java.lang.invoke.MethodHandles;
34import java.nio.ByteBuffer;
35import jdk.nashorn.internal.objects.annotations.Attribute;
36import jdk.nashorn.internal.objects.annotations.Constructor;
37import jdk.nashorn.internal.objects.annotations.Function;
38import jdk.nashorn.internal.objects.annotations.Property;
39import jdk.nashorn.internal.objects.annotations.ScriptClass;
40import jdk.nashorn.internal.objects.annotations.Where;
41import jdk.nashorn.internal.runtime.JSType;
42import jdk.nashorn.internal.runtime.PropertyMap;
43import jdk.nashorn.internal.runtime.ScriptObject;
44import jdk.nashorn.internal.runtime.arrays.ArrayData;
45import jdk.nashorn.internal.runtime.arrays.TypedArrayData;
46
47/**
48 * Uint8 clamped array for TypedArray extension
49 */
50@ScriptClass("Uint8ClampedArray")
51public 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        private int getElem(final int index) {
102            try {
103                return nb.get(index) & 0xff;
104            } catch (final IndexOutOfBoundsException e) {
105                throw new ClassCastException(); //force relink - this works for unoptimistic too
106            }
107        }
108
109        @Override
110        public MethodHandle getElementSetter(final Class<?> elementType) {
111            final MethodHandle setter = super.getElementSetter(elementType); //getContinuousElementSetter(getClass(), setElem(), elementType);
112            if (setter != null) {
113                if (elementType == Object.class) {
114                    return MH.filterArguments(setter, 2, RINT_O);
115                } else if (elementType == double.class) {
116                    return MH.filterArguments(setter, 2, RINT_D);
117                } else if (elementType == long.class) {
118                    return MH.filterArguments(setter, 2, CLAMP_LONG);
119                }
120            }
121            return setter;
122        }
123
124        private void setElem(final int index, final int elem) {
125            try {
126                final byte clamped;
127                if ((elem & 0xffff_ff00) == 0) {
128                    clamped = (byte)elem;
129                } else {
130                    clamped = elem < 0 ? 0 : (byte)0xff;
131                }
132                nb.put(index, clamped);
133            } catch (final IndexOutOfBoundsException e) {
134                //swallow valid array indexes. it's ok.
135                if (index < 0) {
136                    throw new ClassCastException();
137                }
138            }
139        }
140
141        @Override
142        public boolean isClamped() {
143            return true;
144        }
145
146        @Override
147        public boolean isUnsigned() {
148            return true;
149        }
150
151        @Override
152        public int getInt(final int index) {
153            return getElem(index);
154        }
155
156        @Override
157        public long getLong(final int index) {
158            return getInt(index);
159        }
160
161        @Override
162        public double getDouble(final int index) {
163            return getInt(index);
164        }
165
166        @Override
167        public Object getObject(final int index) {
168            return getInt(index);
169        }
170
171        @Override
172        public ArrayData set(final int index, final Object value, final boolean strict) {
173            return set(index, JSType.toNumber(value), strict);
174        }
175
176        @Override
177        public ArrayData set(final int index, final int value, final boolean strict) {
178            setElem(index, value);
179            return this;
180        }
181
182        @Override
183        public ArrayData set(final int index, final long value, final boolean strict) {
184            return set(index, (int)value, strict);
185        }
186
187        @Override
188        public ArrayData set(final int index, final double value, final boolean strict) {
189            return set(index, rint(value), strict);
190        }
191
192        private static double rint(final double rint) {
193            return (int)Math.rint(rint);
194        }
195
196        @SuppressWarnings("unused")
197        private static Object rint(final Object rint) {
198            return rint(JSType.toNumber(rint));
199        }
200
201        @SuppressWarnings("unused")
202        private static long clampLong(final long l) {
203            if(l < 0L) {
204                return 0L;
205            } else if(l > 0xffL) {
206                return 0xffL;
207            }
208            return l;
209        }
210    }
211
212    /**
213     * Constructor
214     *
215     * @param newObj is this typed array instantiated with the new operator
216     * @param self   self reference
217     * @param args   args
218     *
219     * @return new typed array
220     */
221    @Constructor(arity = 1)
222    public static NativeUint8ClampedArray constructor(final boolean newObj, final Object self, final Object... args) {
223        return (NativeUint8ClampedArray)constructorImpl(newObj, args, FACTORY);
224    }
225
226    NativeUint8ClampedArray(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
227        super(buffer, byteOffset, length);
228    }
229
230    @Override
231    protected Factory factory() {
232        return FACTORY;
233    }
234
235    /**
236     * Set values
237     * @param self   self reference
238     * @param array  multiple values of array's type to set
239     * @param offset optional start index, interpreted  0 if undefined
240     * @return undefined
241     */
242    @Function(attributes = Attribute.NOT_ENUMERABLE)
243    protected static Object set(final Object self, final Object array, final Object offset) {
244        return ArrayBufferView.setImpl(self, array, offset);
245    }
246
247    /**
248     * Returns a new TypedArray view of the ArrayBuffer store for this TypedArray,
249     * referencing the elements at begin, inclusive, up to end, exclusive. If either
250     * begin or end is negative, it refers to an index from the end of the array,
251     * as opposed to from the beginning.
252     * <p>
253     * If end is unspecified, the subarray contains all elements from begin to the end
254     * of the TypedArray. The range specified by the begin and end values is clamped to
255     * the valid index range for the current array. If the computed length of the new
256     * TypedArray would be negative, it is clamped to zero.
257     * <p>
258     * The returned TypedArray will be of the same type as the array on which this
259     * method is invoked.
260     *
261     * @param self self reference
262     * @param begin begin position
263     * @param end end position
264     *
265     * @return sub array
266     */
267    @Function(attributes = Attribute.NOT_ENUMERABLE)
268    protected static NativeUint8ClampedArray subarray(final Object self, final Object begin, final Object end) {
269        return (NativeUint8ClampedArray)ArrayBufferView.subarrayImpl(self, begin, end);
270    }
271
272    @Override
273    protected ScriptObject getPrototype(final Global global) {
274        return global.getUint8ClampedArrayPrototype();
275    }
276}
277