@Override public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper, Spliterator<P_IN> spliterator, IntFunction<T[]> generator) { // If the input is already naturally sorted and this operation // naturally sorts then collect the output if (StreamOpFlag.SORTED.isKnown(helper.getStreamAndOpFlags()) && isNaturalSort) { return helper.evaluate(spliterator, false, generator); } else { // @@@ Weak two-pass parallel implementation; parallel collect, parallel sort T[] flattenedData = helper.evaluate(spliterator, true, generator).asArray(generator); Arrays.parallelSort(flattenedData, comparator); return Nodes.node(flattenedData); } }
private static SchemeMapping forColoredMaterial(Material material) { final IntFunction<Item> func = value -> ItemStackBuilder.of(material).name("&f").data(value).build(null); Map<Integer, Item> map = ImmutableMap.<Integer, Item>builder() .put(0, func.apply(0)) .put(1, func.apply(1)) .put(2, func.apply(2)) .put(3, func.apply(3)) .put(4, func.apply(4)) .put(5, func.apply(5)) .put(6, func.apply(6)) .put(7, func.apply(7)) .put(8, func.apply(8)) .put(9, func.apply(9)) .put(10, func.apply(10)) .put(11, func.apply(11)) .put(12, func.apply(12)) .put(13, func.apply(13)) .put(14, func.apply(14)) .put(15, func.apply(15)) .build(); return AbstractSchemeMapping.of(map); }
@Override public final <U> Stream<U> mapToObj(IntFunction<? extends U> mapper) { Objects.requireNonNull(mapper); return new ReferencePipeline.StatelessOp<Integer, U>(this, StreamShape.INT_VALUE, StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) { @Override Sink<Integer> opWrapSink(int flags, Sink<U> sink) { return new Sink.ChainedInt<U>(sink) { @Override public void accept(int t) { downstream.accept(mapper.apply(t)); } }; } }; }
/** * Collect the elements output from the pipeline stage. * * @param generator the array generator to be used to create array instances * @return a flat array-backed Node that holds the collected output elements */ @SuppressWarnings("unchecked") final Node<E_OUT> evaluateToArrayNode(IntFunction<E_OUT[]> generator) { if (linkedOrConsumed) throw new IllegalStateException(MSG_STREAM_LINKED); linkedOrConsumed = true; // If the last intermediate operation is stateful then // evaluate directly to avoid an extra collection step if (isParallel() && previousStage != null && opIsStateful()) { return opEvaluateParallel(previousStage, previousStage.sourceSpliterator(0), generator); } else { return evaluate(sourceSpliterator(0), true, generator); } }
@Test(dataProvider = "intViewProvider") public void testIntGet(String desc, IntFunction<ByteBuffer> fbb, Function<ByteBuffer, IntBuffer> fbi) { ByteBuffer bb = allocate(fbb); IntBuffer vb = fbi.apply(bb); int o = bb.position(); for (int i = 0; i < vb.limit(); i++) { int fromBytes = getIntFromBytes(bb, o + i * 4); int fromMethodView = bb.getInt(o + i * 4); assertValues(i, fromBytes, fromMethodView, bb); int fromBufferView = vb.get(i); assertValues(i, fromMethodView, fromBufferView, bb, vb); } for (int i = 0; i < vb.limit(); i++) { int v = getIntFromBytes(bb, o + i * 4); int a = bb.getInt(); assertValues(i, v, a, bb); int b = vb.get(); assertValues(i, a, b, bb, vb); } }
@Override default Node.OfInt truncate(long from, long to, IntFunction<Integer[]> generator) { if (from == 0 && to == count()) return this; long size = to - from; Spliterator.OfInt spliterator = spliterator(); Node.Builder.OfInt nodeBuilder = Nodes.intBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((IntConsumer) e -> { }); i++) { } if (to == count()) { spliterator.forEachRemaining((IntConsumer) nodeBuilder); } else { for (int i = 0; i < size && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { } } nodeBuilder.end(); return nodeBuilder.build(); }
@Test(dataProvider = "floatViewProvider") public void testFloatGet(String desc, IntFunction<ByteBuffer> fbb, Function<ByteBuffer, FloatBuffer> fbi) { ByteBuffer bb = allocate(fbb); FloatBuffer vb = fbi.apply(bb); int o = bb.position(); for (int i = 0; i < vb.limit(); i++) { float fromBytes = getFloatFromBytes(bb, o + i * 4); float fromMethodView = bb.getFloat(o + i * 4); assertValues(i, fromBytes, fromMethodView, bb); float fromBufferView = vb.get(i); assertValues(i, fromMethodView, fromBufferView, bb, vb); } for (int i = 0; i < vb.limit(); i++) { float v = getFloatFromBytes(bb, o + i * 4); float a = bb.getFloat(); assertValues(i, v, a, bb); float b = vb.get(); assertValues(i, a, b, bb, vb); } }
/** * Return a node describing a subsequence of the elements of this node, * starting at the given inclusive start offset and ending at the given * exclusive end offset. * * @param from The (inclusive) starting offset of elements to include, must * be in range 0..count(). * @param to The (exclusive) end offset of elements to include, must be * in range 0..count(). * @param generator A function to be used to create a new array, if needed, * for reference nodes. * @return the truncated node */ default Node<T> truncate(long from, long to, IntFunction<T[]> generator) { if (from == 0 && to == count()) return this; Spliterator<T> spliterator = spliterator(); long size = to - from; Node.Builder<T> nodeBuilder = Nodes.builder(size, generator); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance(e -> { }); i++) { } if (to == count()) { spliterator.forEachRemaining(nodeBuilder); } else { for (int i = 0; i < size && spliterator.tryAdvance(nodeBuilder); i++) { } } nodeBuilder.end(); return nodeBuilder.build(); }
@Override public <P_IN> Node<Integer> opEvaluateParallel(PipelineHelper<Integer> helper, Spliterator<P_IN> spliterator, IntFunction<Integer[]> generator) { if (StreamOpFlag.SORTED.isKnown(helper.getStreamAndOpFlags())) { return helper.evaluate(spliterator, false, generator); } else { Node.OfInt n = (Node.OfInt) helper.evaluate(spliterator, true, generator); int[] content = n.asPrimitiveArray(); Arrays.parallelSort(content); return Nodes.node(content); } }
@Override public <P_IN> Node<Double> opEvaluateParallel(PipelineHelper<Double> helper, Spliterator<P_IN> spliterator, IntFunction<Double[]> generator) { if (StreamOpFlag.SORTED.isKnown(helper.getStreamAndOpFlags())) { return helper.evaluate(spliterator, false, generator); } else { Node.OfDouble n = (Node.OfDouble) helper.evaluate(spliterator, true, generator); double[] content = n.asPrimitiveArray(); Arrays.parallelSort(content); return Nodes.node(content); } }
@Override public void setBlockBiomeTint(Block block, IntFunction<BlockTint> tintTypeForSubtype) { if (!(block instanceof CSBlock)) return; BlockColors blockColors = Minecraft.getMinecraft().getBlockColors(); CSBlock csBlock = (CSBlock) block; blockColors.registerBlockColorHandler( (state, worldIn, pos, tintIndex) -> { if (worldIn == null || pos == null) return ColorizerFoliage.getFoliageColorBasic(); return tintTypeForSubtype.apply(csBlock.getSubtype(state)).getMultiplier(worldIn, pos); /*if (tintType == BiomeTintType.FOLIAGE) return BiomeColorHelper.getFoliageColorAtPos(worldIn, pos); if (tintType == BiomeTintType.GRASS) return BiomeColorHelper.getGrassColorAtPos(worldIn, pos); if (tintType == BiomeTintType.WATER) return BiomeColorHelper.getWaterColorAtPos(worldIn, pos); return -1;*/ }, block); }
static void writeLineSeparator(Path p, IntFunction<LineSeparator> lineSeparatorGenerator, int lines, Charset cs) throws IOException { BufferedWriter bw = Files.newBufferedWriter(p, cs, StandardOpenOption.APPEND); bw.write(lineSeparatorGenerator.apply(lines - 1).value); bw.flush(); bw.close(); }
TakeWhileTask(AbstractPipeline<P_OUT, P_OUT, ?> op, PipelineHelper<P_OUT> helper, Spliterator<P_IN> spliterator, IntFunction<P_OUT[]> generator) { super(helper, spliterator); this.op = op; this.generator = generator; this.isOrdered = StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags()); }
@SuppressWarnings("unchecked") private static <T> T create(Map<Class<?>, IntFunction<?>> map, Class<T> clazz, int size) { IntFunction<?> intFunction = map.get(clazz); if (intFunction != null) { return (T) intFunction.apply(size); } if ((! Modifier.isAbstract(clazz.getModifiers())) && (Map.class.isAssignableFrom(clazz) || Collection.class.isAssignableFrom(clazz))) { ConstructorInvoker<T> constructor = DioriteReflectionUtils.getConstructor(clazz, false); if (constructor != null) { constructor.ensureAccessible(); IntFunction<T> creator = constructor::invokeWith; map.put(clazz, creator); return creator.apply(size); } } for (Entry<Class<?>, IntFunction<?>> entry : map.entrySet()) { if (clazz.isAssignableFrom(entry.getKey())) { IntFunction<?> function = entry.getValue(); map.put(clazz, function); return (T) function.apply(size); } } throw new YAMLException("Can't create collection: " + clazz); }
@SuppressWarnings("unchecked") ArrayNode(long size, IntFunction<T[]> generator) { if (size >= MAX_ARRAY_SIZE) throw new IllegalArgumentException(BAD_SIZE); this.array = generator.apply((int) size); this.curSize = 0; }
public static <T, R> R[] mapToArray(Collection<T> inputs, Function<? super T, ? extends R> mapper, IntFunction<R[]> arrayGenerator) { R[] result = arrayGenerator.apply(inputs.size()); int idx = 0; for (T t : inputs) { result[idx++] = mapper.apply(t); } return result; }
public <T> T[] readArray(Writeable.Reader<T> reader, IntFunction<T[]> arraySupplier) throws IOException { int length = readArraySize(); T[] values = arraySupplier.apply(length); for (int i = 0; i < length; i++) { values[i] = reader.read(this); } return values; }
@Override default Node.OfInt truncate(long from, long to, IntFunction<Integer[]> generator) { if (from == 0 && to == count()) return this; long size = to - from; Spliterator.OfInt spliterator = spliterator(); Node.Builder.OfInt nodeBuilder = Nodes.intBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((IntConsumer) e -> { }); i++) { } for (int i = 0; (i < size) && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { } nodeBuilder.end(); return nodeBuilder.build(); }
@Override default Node.OfDouble truncate(long from, long to, IntFunction<Double[]> generator) { if (from == 0 && to == count()) return this; long size = to - from; Spliterator.OfDouble spliterator = spliterator(); Node.Builder.OfDouble nodeBuilder = Nodes.doubleBuilder(size); nodeBuilder.begin(size); for (int i = 0; i < from && spliterator.tryAdvance((DoubleConsumer) e -> { }); i++) { } for (int i = 0; (i < size) && spliterator.tryAdvance((DoubleConsumer) nodeBuilder); i++) { } nodeBuilder.end(); return nodeBuilder.build(); }
private static IntFunction<Integer> twoDiceThrows() { return i -> { ThreadLocalRandom random = ThreadLocalRandom.current(); int firstThrow = random.nextInt(1, 7); int secondThrow = random.nextInt(1, 7); return firstThrow + secondThrow; }; }
/** * Collects a Stream of Pairs into a single Pair of arrays, where a given index can be used to access the left * and right parts of the input pairs respectively. */ static <L, R> Collector<Pair<L, R>, Pair<List<L>, List<R>>, Pair<L[], R[]>> toArrays(IntFunction<L[]> leftArrayConstructor, IntFunction<R[]> rightArrayConstructor) { return using( left -> left.stream().toArray(leftArrayConstructor), right -> right.stream().toArray(rightArrayConstructor) ); }
@Override public T[] asArray(IntFunction<T[]> generator) { if (array.length == curSize) { return array; } else { throw new IllegalStateException(); } }
public static <T extends Graph> SymbolGraph<T> loadFromFile(Path p, String separator, IntFunction<T> constructor) { try { return new SymbolGraph<T>(p, separator, constructor); } catch (IOException e) { throw new RuntimeException("Error while parsing file", e); } }
@Override public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper, Spliterator<P_IN> spliterator, IntFunction<T[]> generator) { int flags = helper.getStreamAndOpFlags(); Assert.assertTrue(StreamOpFlag.SIZED.isKnown(flags)); return super.opEvaluateParallel(helper, spliterator, generator); }
@Override final <P_IN> Node<P_OUT> evaluateToNode(PipelineHelper<P_OUT> helper, Spliterator<P_IN> spliterator, boolean flattenTree, IntFunction<P_OUT[]> generator) { return Nodes.collect(helper, spliterator, flattenTree, generator); }
@Override public T[] asArray(IntFunction<T[]> generator) { long size = count(); if (size >= MAX_ARRAY_SIZE) throw new IllegalArgumentException(BAD_SIZE); T[] array = generator.apply((int) size); copyInto(array, 0); return array; }
@Override public Node<T> truncate(long from, long to, IntFunction<T[]> generator) { if (from == 0 && to == count()) return this; long leftCount = left.count(); if (from >= leftCount) return right.truncate(from - leftCount, to - leftCount, generator); else if (to <= leftCount) return left.truncate(from, to, generator); else { return Nodes.conc(getShape(), left.truncate(from, leftCount, generator), right.truncate(0, to - leftCount, generator)); } }
/** * Create a new array using the specified array factory, and copy the * elements into it. */ public E[] asArray(IntFunction<E[]> arrayFactory) { long size = count(); if (size >= Nodes.MAX_ARRAY_SIZE) throw new IllegalArgumentException(Nodes.BAD_SIZE); E[] result = arrayFactory.apply((int) size); copyInto(result, 0); return result; }
/** * {@inheritDoc} * * @implSpec the default implementation invokes the generator to create * an instance of a boxed primitive array with a length of * {@link #count()} and then invokes {@link #copyInto(T[], int)} with * that array at an offset of 0. */ @Override default T[] asArray(IntFunction<T[]> generator) { if (java.util.stream.Tripwire.ENABLED) java.util.stream.Tripwire.trip(getClass(), "{0} calling Node.OfPrimitive.asArray"); long size = count(); if (size >= Nodes.MAX_ARRAY_SIZE) throw new IllegalArgumentException(Nodes.BAD_SIZE); T[] boxed = generator.apply((int) count()); copyInto(boxed, 0); return boxed; }
/** * Creates an INTEGER Printer that wraps the function provided * @param function the function to wrap * @return the newly created function Printer */ public static Printer<Integer> forInt(IntFunction<String> function) { return new Printer<Integer>(FunctionStyle.INTEGER, DEFAULT_NULL) { @Override public final String apply(int input) { return function.apply(input); } }; }
/** * Filters the inputs, maps them given the mapping function and adds them in the array provided * by the generator. */ public static <T, R> R[] filterAndMapToArray(T[] inputs, Predicate<? super T> predicate, Function<? super T, ? extends R> mapper, IntFunction<R[]> arrayGenerator) { List<R> resultList = new ArrayList<>(); for (T t : inputs) { if (predicate.test(t)) { resultList.add(mapper.apply(t)); } } return resultList.toArray(arrayGenerator.apply(resultList.size())); }
public static Bytes readSliceFrom(InputStream streamToDrain, int offset, int len, IntFunction<Bytes.BuilderStream> builderFactory) throws IOException { // the implementation is based on commons-io IOUtils.copyLarge if (len == 0) { return Bytes.empty(); } if (offset > 0) { final long skipped = streamToDrain.skip(offset); if (skipped < offset) return Bytes.empty(); } byte[] readBuffer = new byte[len > 4096 ? 4096 : len]; final int bufferLength = readBuffer.length; int bytesToRead = bufferLength; if (len > 0 && len < bufferLength) { bytesToRead = len; } final Bytes.BuilderStream builder = builderFactory.apply(len); int read; long totalRead = 0; while (bytesToRead > 0 && -1 != (read = streamToDrain.read(readBuffer, 0, bytesToRead))) { builder.write(readBuffer, 0, read); totalRead += read; if (len > 0) { // only adjust length if not reading to the end // Note the cast must work because buffer.length is an integer bytesToRead = (int) Math.min(len - totalRead, bufferLength); } } return builder.toBytes(); }
SliceTask(AbstractPipeline<P_OUT, P_OUT, ?> op, PipelineHelper<P_OUT> helper, Spliterator<P_IN> spliterator, IntFunction<P_OUT[]> generator, long offset, long size) { super(helper, spliterator); this.op = op; this.generator = generator; this.targetOffset = offset; this.targetSize = size; }