All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.reactivex.rxjava3.internal.functions.Functions Maven / Gradle / Ivy

There is a newer version: 3.1.9
Show newest version
/*
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
 * the License for the specific language governing permissions and limitations under the License.
 */

package io.reactivex.rxjava3.internal.functions;

import java.util.*;
import java.util.concurrent.*;

import org.reactivestreams.Subscription;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException;
import io.reactivex.rxjava3.functions.*;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import io.reactivex.rxjava3.schedulers.Timed;

/**
 * Utility methods to convert the BiFunction, Function3..Function9 instances to Function of Object array.
 */
public final class Functions {

    /** Utility class. */
    private Functions() {
        throw new IllegalStateException("No instances!");
    }

    @NonNull
    public static  Function toFunction(@NonNull BiFunction f) {
        return new Array2Func<>(f);
    }

    @NonNull
    public static  Function toFunction(@NonNull Function3 f) {
        return new Array3Func<>(f);
    }

    @NonNull
    public static  Function toFunction(@NonNull Function4 f) {
        return new Array4Func<>(f);
    }

    @NonNull
    public static  Function toFunction(@NonNull Function5 f) {
        return new Array5Func<>(f);
    }

    @NonNull
    public static  Function toFunction(
            @NonNull Function6 f) {
        return new Array6Func<>(f);
    }

    @NonNull
    public static  Function toFunction(
            @NonNull Function7 f) {
        return new Array7Func<>(f);
    }

    @NonNull
    public static  Function toFunction(
            @NonNull Function8 f) {
        return new Array8Func<>(f);
    }

    @NonNull
    public static  Function toFunction(
            @NonNull Function9 f) {
        return new Array9Func<>(f);
    }

    /** A singleton identity function. */
    static final Function IDENTITY = new Identity();

    /**
     * Returns an identity function that simply returns its argument.
     * @param  the input and output value type
     * @return the identity function
     */
    @SuppressWarnings("unchecked")
    @NonNull
    public static  Function identity() {
        return (Function)IDENTITY;
    }

    public static final Runnable EMPTY_RUNNABLE = new EmptyRunnable();

    public static final Action EMPTY_ACTION = new EmptyAction();

    static final Consumer EMPTY_CONSUMER = new EmptyConsumer();

    /**
     * Returns an empty consumer that does nothing.
     * @param  the consumed value type, the value is ignored
     * @return an empty consumer that does nothing.
     */
    @SuppressWarnings("unchecked")
    public static  Consumer emptyConsumer() {
        return (Consumer)EMPTY_CONSUMER;
    }

    public static final Consumer ERROR_CONSUMER = new ErrorConsumer();

    /**
     * Wraps the consumed Throwable into an OnErrorNotImplementedException and
     * signals it to the plugin error handler.
     */
    public static final Consumer ON_ERROR_MISSING = new OnErrorMissingConsumer();

    public static final LongConsumer EMPTY_LONG_CONSUMER = new EmptyLongConsumer();

    static final Predicate ALWAYS_TRUE = new TruePredicate();

    static final Predicate ALWAYS_FALSE = new FalsePredicate();

    static final Supplier NULL_SUPPLIER = new NullProvider();

    @SuppressWarnings("unchecked")
    @NonNull
    public static  Predicate alwaysTrue() {
        return (Predicate)ALWAYS_TRUE;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    public static  Predicate alwaysFalse() {
        return (Predicate)ALWAYS_FALSE;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    public static  Supplier nullSupplier() {
        return (Supplier)NULL_SUPPLIER;
    }

    static final class FutureAction implements Action {
        final Future future;

        FutureAction(Future future) {
            this.future = future;
        }

        @Override
        public void run() throws Exception {
            future.get();
        }
    }

    /**
     * Wraps the blocking get call of the Future into an Action.
     * @param future the future to call get() on, not null
     * @return the new Action instance
     */
    @NonNull
    public static Action futureAction(@NonNull Future future) {
        return new FutureAction(future);
    }

    static final class JustValue implements Callable, Supplier, Function {
        final U value;

        JustValue(U value) {
            this.value = value;
        }

        @Override
        public U call() {
            return value;
        }

        @Override
        public U apply(T t) {
            return value;
        }

        @Override
        public U get() {
            return value;
        }
    }

    /**
     * Returns a Callable that returns the given value.
     * @param  the value type
     * @param value the value to return
     * @return the new Callable instance
     */
    @NonNull
    public static  Callable justCallable(@NonNull T value) {
        return new JustValue<>(value);
    }

    /**
     * Returns a Supplier that returns the given value.
     * @param  the value type
     * @param value the value to return
     * @return the new Callable instance
     */
    @NonNull
    public static  Supplier justSupplier(@NonNull T value) {
        return new JustValue<>(value);
    }

    /**
     * Returns a Function that ignores its parameter and returns the given value.
     * @param  the function's input type
     * @param  the value and return type of the function
     * @param value the value to return
     * @return the new Function instance
     */
    @NonNull
    public static  Function justFunction(@NonNull U value) {
        return new JustValue<>(value);
    }

    static final class CastToClass implements Function {
        final Class clazz;

        CastToClass(Class clazz) {
            this.clazz = clazz;
        }

        @Override
        public U apply(T t) {
            return clazz.cast(t);
        }
    }

    /**
     * Returns a function that cast the incoming values via a Class object.
     * @param  the input value type
     * @param  the output and target type
     * @param target the target class
     * @return the new Function instance
     */
    @NonNull
    public static  Function castFunction(@NonNull Class target) {
        return new CastToClass<>(target);
    }

    static final class ArrayListCapacityCallable implements Supplier> {
        final int capacity;

        ArrayListCapacityCallable(int capacity) {
            this.capacity = capacity;
        }

        @Override
        public List get() {
            return new ArrayList<>(capacity);
        }
    }

    public static  Supplier> createArrayList(int capacity) {
        return new ArrayListCapacityCallable<>(capacity);
    }

    static final class EqualsPredicate implements Predicate {
        final T value;

        EqualsPredicate(T value) {
            this.value = value;
        }

        @Override
        public boolean test(T t) {
            return Objects.equals(t, value);
        }
    }

    public static  Predicate equalsWith(T value) {
        return new EqualsPredicate<>(value);
    }

    enum HashSetSupplier implements Supplier> {
        INSTANCE;
        @Override
        public Set get() {
            return new HashSet<>();
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static  Supplier> createHashSet() {
        return (Supplier)HashSetSupplier.INSTANCE;
    }

    static final class NotificationOnNext implements Consumer {
        final Consumer> onNotification;

        NotificationOnNext(Consumer> onNotification) {
            this.onNotification = onNotification;
        }

        @Override
        public void accept(T v) throws Throwable {
            onNotification.accept(Notification.createOnNext(v));
        }
    }

    static final class NotificationOnError implements Consumer {
        final Consumer> onNotification;

        NotificationOnError(Consumer> onNotification) {
            this.onNotification = onNotification;
        }

        @Override
        public void accept(Throwable v) throws Throwable {
            onNotification.accept(Notification.createOnError(v));
        }
    }

    static final class NotificationOnComplete implements Action {
        final Consumer> onNotification;

        NotificationOnComplete(Consumer> onNotification) {
            this.onNotification = onNotification;
        }

        @Override
        public void run() throws Throwable {
            onNotification.accept(Notification.createOnComplete());
        }
    }

    public static  Consumer notificationOnNext(Consumer> onNotification) {
        return new NotificationOnNext<>(onNotification);
    }

    public static  Consumer notificationOnError(Consumer> onNotification) {
        return new NotificationOnError<>(onNotification);
    }

    public static  Action notificationOnComplete(Consumer> onNotification) {
        return new NotificationOnComplete<>(onNotification);
    }

    static final class ActionConsumer implements Consumer {
        final Action action;

        ActionConsumer(Action action) {
            this.action = action;
        }

        @Override
        public void accept(T t) throws Throwable {
            action.run();
        }
    }

    public static  Consumer actionConsumer(Action action) {
        return new ActionConsumer<>(action);
    }

    static final class ClassFilter implements Predicate {
        final Class clazz;

        ClassFilter(Class clazz) {
            this.clazz = clazz;
        }

        @Override
        public boolean test(T t) {
            return clazz.isInstance(t);
        }
    }

    public static  Predicate isInstanceOf(Class clazz) {
        return new ClassFilter<>(clazz);
    }

    static final class BooleanSupplierPredicateReverse implements Predicate {
        final BooleanSupplier supplier;

        BooleanSupplierPredicateReverse(BooleanSupplier supplier) {
            this.supplier = supplier;
        }

        @Override
        public boolean test(T t) throws Throwable {
            return !supplier.getAsBoolean();
        }
    }

    public static  Predicate predicateReverseFor(BooleanSupplier supplier) {
        return new BooleanSupplierPredicateReverse<>(supplier);
    }

    static final class TimestampFunction implements Function> {
        final TimeUnit unit;

        final Scheduler scheduler;

        TimestampFunction(TimeUnit unit, Scheduler scheduler) {
            this.unit = unit;
            this.scheduler = scheduler;
        }

        @Override
        public Timed apply(T t) {
            return new Timed<>(t, scheduler.now(unit), unit);
        }
    }

    public static  Function> timestampWith(TimeUnit unit, Scheduler scheduler) {
        return new TimestampFunction<>(unit, scheduler);
    }

    static final class ToMapKeySelector implements BiConsumer, T> {
        private final Function keySelector;

        ToMapKeySelector(Function keySelector) {
            this.keySelector = keySelector;
        }

        @Override
        public void accept(Map m, T t) throws Throwable {
            K key = keySelector.apply(t);
            m.put(key, t);
        }
    }

    public static  BiConsumer, T> toMapKeySelector(final Function keySelector) {
        return new ToMapKeySelector<>(keySelector);
    }

    static final class ToMapKeyValueSelector implements BiConsumer, T> {
        private final Function valueSelector;
        private final Function keySelector;

        ToMapKeyValueSelector(Function valueSelector,
                Function keySelector) {
            this.valueSelector = valueSelector;
            this.keySelector = keySelector;
        }

        @Override
        public void accept(Map m, T t) throws Throwable {
            K key = keySelector.apply(t);
            V value = valueSelector.apply(t);
            m.put(key, value);
        }
    }

    public static  BiConsumer, T> toMapKeyValueSelector(final Function keySelector, final Function valueSelector) {
        return new ToMapKeyValueSelector<>(valueSelector, keySelector);
    }

    static final class ToMultimapKeyValueSelector implements BiConsumer>, T> {
        private final Function> collectionFactory;
        private final Function valueSelector;
        private final Function keySelector;

        ToMultimapKeyValueSelector(Function> collectionFactory,
                Function valueSelector, Function keySelector) {
            this.collectionFactory = collectionFactory;
            this.valueSelector = valueSelector;
            this.keySelector = keySelector;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void accept(Map> m, T t) throws Throwable {
            K key = keySelector.apply(t);

            Collection coll = m.get(key);
            if (coll == null) {
                coll = (Collection)collectionFactory.apply(key);
                m.put(key, coll);
            }

            V value = valueSelector.apply(t);

            coll.add(value);
        }
    }

    public static  BiConsumer>, T> toMultimapKeyValueSelector(
            final Function keySelector, final Function valueSelector,
            final Function> collectionFactory) {
        return new ToMultimapKeyValueSelector<>(collectionFactory, valueSelector, keySelector);
    }

    enum NaturalComparator implements Comparator {
        INSTANCE;

        @SuppressWarnings("unchecked")
        @Override
        public int compare(Object o1, Object o2) {
            return ((Comparable)o1).compareTo(o2);
        }
    }

    @SuppressWarnings("unchecked")
    public static  Comparator naturalComparator() {
        return (Comparator)NaturalComparator.INSTANCE;
    }

    static final class ListSorter implements Function, List> {
        final Comparator comparator;

        ListSorter(Comparator comparator) {
            this.comparator = comparator;
        }

        @Override
        public List apply(List v) {
            Collections.sort(v, comparator);
            return v;
        }
    }

    public static  Function, List> listSorter(final Comparator comparator) {
        return new ListSorter<>(comparator);
    }

    public static final Consumer REQUEST_MAX = new MaxRequestSubscription();

    static final class Array2Func implements Function {
        final BiFunction f;

        Array2Func(BiFunction f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 2) {
                throw new IllegalArgumentException("Array of size 2 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1]);
        }
    }

    static final class Array3Func implements Function {
        final Function3 f;

        Array3Func(Function3 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 3) {
                throw new IllegalArgumentException("Array of size 3 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2]);
        }
    }

    static final class Array4Func implements Function {
        final Function4 f;

        Array4Func(Function4 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 4) {
                throw new IllegalArgumentException("Array of size 4 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3]);
        }
    }

    static final class Array5Func implements Function {
        private final Function5 f;

        Array5Func(Function5 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 5) {
                throw new IllegalArgumentException("Array of size 5 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4]);
        }
    }

    static final class Array6Func implements Function {
        final Function6 f;

        Array6Func(Function6 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 6) {
                throw new IllegalArgumentException("Array of size 6 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4], (T6)a[5]);
        }
    }

    static final class Array7Func implements Function {
        final Function7 f;

        Array7Func(Function7 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 7) {
                throw new IllegalArgumentException("Array of size 7 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4], (T6)a[5], (T7)a[6]);
        }
    }

    static final class Array8Func implements Function {
        final Function8 f;

        Array8Func(Function8 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 8) {
                throw new IllegalArgumentException("Array of size 8 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4], (T6)a[5], (T7)a[6], (T8)a[7]);
        }
    }

    static final class Array9Func implements Function {
        final Function9 f;

        Array9Func(Function9 f) {
            this.f = f;
        }

        @SuppressWarnings("unchecked")
        @Override
        public R apply(Object[] a) throws Throwable {
            if (a.length != 9) {
                throw new IllegalArgumentException("Array of size 9 expected but got " + a.length);
            }
            return f.apply((T1)a[0], (T2)a[1], (T3)a[2], (T4)a[3], (T5)a[4], (T6)a[5], (T7)a[6], (T8)a[7], (T9)a[8]);
        }
    }

    static final class Identity implements Function {
        @Override
        public Object apply(Object v) {
            return v;
        }

        @Override
        public String toString() {
            return "IdentityFunction";
        }
    }

    static final class EmptyRunnable implements Runnable {
        @Override
        public void run() { }

        @Override
        public String toString() {
            return "EmptyRunnable";
        }
    }

    static final class EmptyAction implements Action {
        @Override
        public void run() { }

        @Override
        public String toString() {
            return "EmptyAction";
        }
    }

    static final class EmptyConsumer implements Consumer {
        @Override
        public void accept(Object v) { }

        @Override
        public String toString() {
            return "EmptyConsumer";
        }
    }

    static final class ErrorConsumer implements Consumer {
        @Override
        public void accept(Throwable error) {
            RxJavaPlugins.onError(error);
        }
    }

    static final class OnErrorMissingConsumer implements Consumer {
        @Override
        public void accept(Throwable error) {
            RxJavaPlugins.onError(new OnErrorNotImplementedException(error));
        }
    }

    static final class EmptyLongConsumer implements LongConsumer {
        @Override
        public void accept(long v) { }
    }

    static final class TruePredicate implements Predicate {
        @Override
        public boolean test(Object o) {
            return true;
        }
    }

    static final class FalsePredicate implements Predicate {
        @Override
        public boolean test(Object o) {
            return false;
        }
    }

    static final class NullProvider implements Supplier {
        @Override
        public Object get() {
            return null;
        }
    }

    static final class MaxRequestSubscription implements Consumer {
        @Override
        public void accept(Subscription t) {
            t.request(Long.MAX_VALUE);
        }
    }

    @SuppressWarnings("unchecked")
    public static  Consumer boundedConsumer(int bufferSize) {
        return (Consumer) new BoundedConsumer(bufferSize);
    }

    public static class BoundedConsumer implements Consumer {

        final int bufferSize;

        BoundedConsumer(int bufferSize) {
            this.bufferSize = bufferSize;
        }

        @Override
        public void accept(Subscription s) {
            s.request(bufferSize);
        }
    }
}