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

org.javimmutable.collections.list.JImmutableTreeList Maven / Gradle / Ivy

Go to download

Library providing immutable/persistent collection classes for Java. While collections are immutable they provide methods for adding and removing values by creating new modified copies of themselves. Each copy shares almost all of its structure with other copies to minimize memory consumption.

The newest version!
///###////////////////////////////////////////////////////////////////////////
//
// Burton Computer Corporation
// http://www.burton-computer.com
//
// Copyright (c) 2021, Burton Computer Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//
//     Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in
//     the documentation and/or other materials provided with the
//     distribution.
//
//     Neither the name of the Burton Computer Corporation nor the names
//     of its contributors may be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package org.javimmutable.collections.list;

import org.javimmutable.collections.Func1;
import org.javimmutable.collections.Func2;
import org.javimmutable.collections.Holder;
import org.javimmutable.collections.Indexed;
import org.javimmutable.collections.JImmutableList;
import org.javimmutable.collections.Proc1Throws;
import org.javimmutable.collections.SplitableIterator;
import org.javimmutable.collections.Sum1Throws;
import org.javimmutable.collections.common.ListAdaptor;
import org.javimmutable.collections.common.MutableDelta;
import org.javimmutable.collections.common.StreamConstants;
import org.javimmutable.collections.indexed.IndexedList;
import org.javimmutable.collections.iterators.IteratorHelper;
import org.javimmutable.collections.serialization.JImmutableListProxy;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.ThreadSafe;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collector;

import static org.javimmutable.collections.list.TreeBuilder.*;

@Immutable
public class JImmutableTreeList
    implements JImmutableList,
               Serializable
{
    @SuppressWarnings("unchecked")
    private static final JImmutableTreeList EMPTY = new JImmutableTreeList(EmptyNode.instance());
    private static final long serialVersionUID = -121805;

    private final AbstractNode root;

    private JImmutableTreeList(@Nonnull AbstractNode root)
    {
        this.root = root;
    }

    @SuppressWarnings("unchecked")
    @Nonnull
    public static  JImmutableTreeList of()
    {
        return EMPTY;
    }

    @Nonnull
    public static  JImmutableTreeList of(@Nonnull Indexed values)
    {
        return create(nodeFromIndexed(values, 0, values.size()));
    }

    @Nonnull
    public static  JImmutableTreeList of(@Nonnull Indexed values,
                                               int offset,
                                               int limit)
    {
        return create(nodeFromIndexed(values, offset, limit));
    }

    @Nonnull
    public static  JImmutableTreeList of(@Nonnull Iterator values)
    {
        return create(nodeFromIterator(values));
    }

    @Nonnull
    public static  ListBuilder listBuilder()
    {
        return new ListBuilder<>();
    }

    @Nonnull
    public static  Collector> createListCollector()
    {
        return Collector., JImmutableList>of(() -> new ListBuilder<>(),
                                                                  (b, v) -> b.add(v),
                                                                  (b1, b2) -> b1.combineWith(b2),
                                                                  b -> b.build());
    }

    @Nonnull
    static  JImmutableTreeList create(@Nonnull AbstractNode root)
    {
        if (root.isEmpty()) {
            return of();
        } else {
            return new JImmutableTreeList<>(root);
        }
    }

    @Nonnull
    @Override
    public JImmutableTreeList assign(int index,
                                        @Nullable T value)
    {
        return new JImmutableTreeList<>(root.assign(index, value));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insert(@Nullable T value)
    {
        return new JImmutableTreeList<>(root.append(value));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insert(int index,
                                        @Nullable T value)
    {
        return new JImmutableTreeList<>(root.insert(index, value));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertFirst(@Nullable T value)
    {
        return new JImmutableTreeList<>(root.prepend(value));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertLast(@Nullable T value)
    {
        return new JImmutableTreeList<>(root.append(value));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAll(@Nonnull Iterable values)
    {
        return insertAllLast(nodeFromIterable(values));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAll(@Nonnull Iterator values)
    {
        return insertAllLast(nodeFromIterator(values));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAll(int index,
                                           @Nonnull Iterable values)
    {
        return insertAll(index, nodeFromIterable(values));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAll(int index,
                                           @Nonnull Iterator values)
    {
        return insertAll(index, nodeFromIterator(values));
    }

    @Nonnull
    private JImmutableTreeList insertAll(int index,
                                            @Nonnull AbstractNode other)
    {
        return create(root.prefix(index).append(other).append(root.suffix(index)));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAllFirst(@Nonnull Iterable values)
    {
        return insertAllFirst(nodeFromIterable(values));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAllFirst(@Nonnull Iterator values)
    {
        return insertAllFirst(nodeFromIterator(values));
    }

    @Nonnull
    private JImmutableTreeList insertAllFirst(@Nonnull AbstractNode other)
    {
        return create(root.prepend(other));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAllLast(@Nonnull Iterable values)
    {
        return insertAllLast(nodeFromIterable(values));
    }

    @Nonnull
    @Override
    public JImmutableTreeList insertAllLast(@Nonnull Iterator values)
    {
        return insertAllLast(nodeFromIterator(values));
    }

    @Nonnull
    private JImmutableTreeList insertAllLast(@Nonnull AbstractNode other)
    {
        return create(root.append(other));
    }

    @Nonnull
    @Override
    public JImmutableTreeList deleteFirst()
    {
        return create(root.deleteFirst());
    }

    @Nonnull
    @Override
    public JImmutableTreeList deleteLast()
    {
        return create(root.deleteLast());
    }

    @Nonnull
    @Override
    public JImmutableTreeList delete(int index)
    {
        return create(root.delete(index));
    }

    @Nonnull
    @Override
    public JImmutableTreeList deleteAll()
    {
        return of();
    }

    @Nonnull
    @Override
    public JImmutableList reverse()
    {
        final AbstractNode newRoot = root.reverse();
        if (newRoot == root) {
            return this;
        } else {
            return new JImmutableTreeList<>(newRoot);
        }
    }

    @Override
    public  JImmutableTreeList transform(@Nonnull Func1 transform)
    {
        final ListBuilder builder = new ListBuilder<>();
        root.forEach(t -> builder.add(transform.apply(t)));
        return builder.build();
    }

    @Override
    public  JImmutableTreeList transformSome(@Nonnull Func1> transform)
    {
        final ListBuilder builder = new ListBuilder<>();
        root.forEach(t -> transform.apply(t).ifPresent(builder::add));
        return builder.build();
    }

    @Override
    public int size()
    {
        return root.size();
    }

    @Override
    public T get(int index)
    {
        return root.get(index);
    }

    @Override
    public boolean isEmpty()
    {
        return root.isEmpty();
    }

    @Override
    public boolean isNonEmpty()
    {
        return !root.isEmpty();
    }

    @Nonnull
    @Override
    public JImmutableTreeList select(@Nonnull Predicate predicate)
    {
        final ListBuilder answer = listBuilder();
        root.forEach(value -> {
            if (predicate.test(value)) {
                answer.add(value);
            }
        });
        return answer.size() == size() ? this : answer.build();
    }

    @Nonnull
    @Override
    public JImmutableTreeList reject(@Nonnull Predicate predicate)
    {
        final MutableDelta index = new MutableDelta();
        final AbstractNode newRoot = root.reduce(root, (answer, value) -> {
            assert value == answer.get(index.getValue());
            if (predicate.test(value)) {
                answer = answer.delete(index.getValue());
            } else {
                index.add(1);
            }
            return answer;
        });
        if (newRoot.isEmpty()) {
            return of();
        } else if (newRoot == root) {
            return this;
        } else {
            return new JImmutableTreeList<>(newRoot);
        }
    }

    @Nonnull
    @Override
    public JImmutableTreeList prefix(int limit)
    {
        return create(root.prefix(limit));
    }

    @Nonnull
    @Override
    public JImmutableTreeList suffix(int offset)
    {
        return create(root.suffix(offset));
    }

    @Nonnull
    @Override
    public JImmutableTreeList middle(int offset,
                                        int limit)
    {
        return create(root.prefix(limit).suffix(offset));
    }

    @Nonnull
    @Override
    public JImmutableList slice(int offset,
                                   int limit)
    {
        final int size = root.size();
        if (offset < 0) {
            offset = size + offset;
        }
        if (limit < 0) {
            limit = size + limit + 1;
        }
        if (offset < 0) {
            offset = 0;
        } else if (offset > size) {
            offset = size;
        }
        if (limit < offset) {
            limit = offset;
        } else if (limit > size) {
            limit = size;
        }
        return middle(offset, limit);
    }

    @Nonnull
    @Override
    public List getList()
    {
        return new ListAdaptor<>(this);
    }

    @Nonnull
    @Override
    public JImmutableList getInsertableSelf()
    {
        return this;
    }

    @Override
    public void checkInvariants()
    {
        root.checkInvariants();
    }

    @Override
    @Nonnull
    public SplitableIterator iterator()
    {
        return root.iterator();
    }

    @Override
    public int getSpliteratorCharacteristics()
    {
        return StreamConstants.SPLITERATOR_ORDERED;
    }

    @Override
    public boolean equals(Object o)
    {
        return (o == this) || ((o instanceof JImmutableList) && IteratorHelper.iteratorEquals(iterator(), ((JImmutableList)o).iterator()));
    }

    @Override
    public int hashCode()
    {
        return IteratorHelper.iteratorHashCode(iterator());
    }

    @Override
    public String toString()
    {
        return IteratorHelper.iteratorToString(iterator());
    }

    private Object writeReplace()
    {
        return new JImmutableListProxy(this);
    }

    @SuppressWarnings("unchecked")
    @Nonnull
    private AbstractNode nodeFromIterable(@Nonnull Iterable values)
    {
        AbstractNode otherRoot;
        if (values instanceof JImmutableTreeList) {
            otherRoot = ((JImmutableTreeList)values).root;
        } else if (values instanceof List) {
            otherRoot = TreeBuilder.nodeFromIndexed(IndexedList.retained((List)values));
        } else {
            otherRoot = nodeFromIterator(values.iterator());
        }
        return otherRoot;
    }

    @Override
    public void forEach(Consumer action)
    {
        root.forEach(action);
    }

    @Override
    public  void forEachThrows(@Nonnull Proc1Throws proc)
        throws E
    {
        root.forEachThrows(proc);
    }

    @Override
    public  V reduce(V initialValue,
                        Func2 accumulator)
    {
        return root.reduce(initialValue, accumulator);
    }

    @Override
    public  V reduceThrows(V initialValue,
                                                   Sum1Throws accumulator)
        throws E
    {
        return root.reduceThrows(initialValue, accumulator);
    }

    @ThreadSafe
    public static class ListBuilder
        implements JImmutableList.Builder
    {
        private final TreeBuilder builder = new TreeBuilder<>();

        @Nonnull
        @Override
        public synchronized JImmutableTreeList build()
        {
            return create(builder.build());
        }

        @Nonnull
        public synchronized ListBuilder combineWith(@Nonnull ListBuilder other)
        {
            builder.combineWith(other.builder);
            return this;
        }

        @Override
        public synchronized int size()
        {
            return builder.size();
        }

        @Nonnull
        @Override
        public synchronized ListBuilder add(T value)
        {
            builder.add(value);
            return this;
        }

        @Nonnull
        @Override
        public synchronized ListBuilder add(Iterator source)
        {
            builder.add(source);
            return this;
        }

        @Nonnull
        @Override
        public synchronized ListBuilder add(Iterable source)
        {
            builder.add(source);
            return this;
        }

        @Nonnull
        @Override
        public synchronized  ListBuilder add(K... source)
        {
            builder.add(source);
            return this;
        }

        @Nonnull
        @Override
        public synchronized ListBuilder add(Indexed source,
                                               int offset,
                                               int limit)
        {
            builder.add(source, offset, limit);
            return this;
        }

        @Nonnull
        @Override
        public synchronized ListBuilder add(Indexed source)
        {
            builder.add(source);
            return this;
        }

        @Nonnull
        @Override
        public synchronized ListBuilder clear()
        {
            builder.clear();
            return this;
        }

        public synchronized void checkInvariants()
        {
            builder.checkInvariants();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy