NativeUint8ClampedArray.java revision 1800:ac561634520e
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
86        private Uint8ClampedArrayData(final ByteBuffer nb, final int start, final int end) {
87            super((nb.position(start).limit(end)).slice(), end - start);
88        }
89
90        @Override
91        protected MethodHandle getGetElem() {
92            return GET_ELEM;
93        }
94
95        @Override
96        protected MethodHandle getSetElem() {
97            return SET_ELEM;
98        }
99
100        @Override
101        public Class<?> getElementType() {
102            return int.class;
103        }
104
105        @Override
106        public Class<?> getBoxedElementType() {
107            return int.class;
108        }
109
110        private int getElem(final int index) {
111            try {
112                return nb.get(index) & 0xff;
113            } catch (final IndexOutOfBoundsException e) {
114                throw new ClassCastException(); //force relink - this works for unoptimistic too
115            }
116        }
117
118        @Override
119        public MethodHandle getElementSetter(final Class<?> elementType) {
120            final MethodHandle setter = super.getElementSetter(elementType); //getContinuousElementSetter(getClass(), setElem(), elementType);
121            if (setter != null) {
122                if (elementType == Object.class) {
123                    return MH.filterArguments(setter, 2, RINT_O);
124                } else if (elementType == double.class) {
125                    return MH.filterArguments(setter, 2, RINT_D);
126                }
127            }
128            return setter;
129        }
130
131        private void setElem(final int index, final int elem) {
132            try {
133                if (index < nb.limit()) {
134                    final byte clamped;
135                    if ((elem & 0xffff_ff00) == 0) {
136                        clamped = (byte) elem;
137                    } else {
138                        clamped = elem < 0 ? 0 : (byte) 0xff;
139                    }
140                    nb.put(index, clamped);
141                }
142            } catch (final IndexOutOfBoundsException e) {
143                throw new ClassCastException();
144            }
145        }
146
147        @Override
148        public boolean isClamped() {
149            return true;
150        }
151
152        @Override
153        public boolean isUnsigned() {
154            return true;
155        }
156
157        @Override
158        public int getInt(final int index) {
159            return getElem(index);
160        }
161
162        @Override
163        public int getIntOptimistic(final int index, final int programPoint) {
164            return getElem(index);
165        }
166
167        @Override
168        public double getDouble(final int index) {
169            return getInt(index);
170        }
171
172        @Override
173        public double getDoubleOptimistic(final int index, final int programPoint) {
174            return getElem(index);
175        }
176
177        @Override
178        public Object getObject(final int index) {
179            return getInt(index);
180        }
181
182        @Override
183        public ArrayData set(final int index, final Object value, final boolean strict) {
184            return set(index, JSType.toNumber(value), strict);
185        }
186
187        @Override
188        public ArrayData set(final int index, final int value, final boolean strict) {
189            setElem(index, value);
190            return this;
191        }
192
193        @Override
194        public ArrayData set(final int index, final double value, final boolean strict) {
195            return set(index, (int) rint(value), strict);
196        }
197
198        private static double rint(final double rint) {
199            return (int)Math.rint(rint);
200        }
201
202        @SuppressWarnings("unused")
203        private static Object rint(final Object rint) {
204            return rint(JSType.toNumber(rint));
205        }
206
207    }
208
209    /**
210     * Constructor
211     *
212     * @param newObj is this typed array instantiated with the new operator
213     * @param self   self reference
214     * @param args   args
215     *
216     * @return new typed array
217     */
218    @Constructor(arity = 1)
219    public static NativeUint8ClampedArray constructor(final boolean newObj, final Object self, final Object... args) {
220        return (NativeUint8ClampedArray)constructorImpl(newObj, args, FACTORY);
221    }
222
223    NativeUint8ClampedArray(final NativeArrayBuffer buffer, final int byteOffset, final int length) {
224        super(buffer, byteOffset, length);
225    }
226
227    @Override
228    protected Factory factory() {
229        return FACTORY;
230    }
231
232    /**
233     * Set values
234     * @param self   self reference
235     * @param array  multiple values of array's type to set
236     * @param offset optional start index, interpreted  0 if undefined
237     * @return undefined
238     */
239    @Function(attributes = Attribute.NOT_ENUMERABLE)
240    protected static Object set(final Object self, final Object array, final Object offset) {
241        return ArrayBufferView.setImpl(self, array, offset);
242    }
243
244    /**
245     * Returns a new TypedArray view of the ArrayBuffer store for this TypedArray,
246     * referencing the elements at begin, inclusive, up to end, exclusive. If either
247     * begin or end is negative, it refers to an index from the end of the array,
248     * as opposed to from the beginning.
249     * <p>
250     * If end is unspecified, the subarray contains all elements from begin to the end
251     * of the TypedArray. The range specified by the begin and end values is clamped to
252     * the valid index range for the current array. If the computed length of the new
253     * TypedArray would be negative, it is clamped to zero.
254     * <p>
255     * The returned TypedArray will be of the same type as the array on which this
256     * method is invoked.
257     *
258     * @param self self reference
259     * @param begin begin position
260     * @param end end position
261     *
262     * @return sub array
263     */
264    @Function(attributes = Attribute.NOT_ENUMERABLE)
265    protected static NativeUint8ClampedArray subarray(final Object self, final Object begin, final Object end) {
266        return (NativeUint8ClampedArray)ArrayBufferView.subarrayImpl(self, begin, end);
267    }
268
269    @Override
270    protected ScriptObject getPrototype(final Global global) {
271        return global.getUint8ClampedArrayPrototype();
272    }
273}
274