cn.wjybxx.dson.DsonArray Maven / Gradle / Ivy
/*
* Copyright 2023-2024 wjybxx([email protected])
*
* 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 cn.wjybxx.dson;
import cn.wjybxx.dson.internal.ValuesPolicy;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.RandomAccess;
/**
* @author wjybxx
* date - 2023/4/19
*/
public class DsonArray extends AbstractDsonArray implements RandomAccess {
private final DsonHeader header;
public DsonArray() {
this(new ArrayList<>(), ValuesPolicy.SOURCE, new DsonHeader<>());
}
public DsonArray(int initCapacity) {
this(new ArrayList<>(initCapacity), ValuesPolicy.SOURCE, new DsonHeader<>());
}
public DsonArray(DsonArray src) {
this(src.values, ValuesPolicy.COPY, new DsonHeader<>(src.getHeader()));
}
private DsonArray(List values, ValuesPolicy policy, DsonHeader header) {
super(values, policy);
this.header = Objects.requireNonNull(header);
}
//
private static final DsonArray> EMPTY = new DsonArray<>(List.of(), ValuesPolicy.IMMUTABLE, DsonHeader.empty());
public static DsonArray toImmutable(DsonArray src) {
return new DsonArray<>(src.values, ValuesPolicy.IMMUTABLE, DsonHeader.toImmutable(src.getHeader()));
}
@SuppressWarnings("unchecked")
public static DsonArray empty() {
return (DsonArray) EMPTY;
}
@Nonnull
@Override
public final DsonType getDsonType() {
return DsonType.ARRAY;
}
@Nonnull
public DsonHeader getHeader() {
return header;
}
@Override
public DsonArray append(DsonValue dsonValue) {
add(dsonValue);
return this;
}
public DsonArray slice(int skip) {
if (skip < 0) throw new IllegalArgumentException("skip cant be negative");
if (skip >= values.size()) {
return new DsonArray<>(0);
}
List dsonValues = values.subList(skip, values.size());
return new DsonArray<>(dsonValues, ValuesPolicy.COPY, new DsonHeader<>());
}
public DsonArray slice(int skip, int count) {
if (skip < 0) throw new IllegalArgumentException("skip cant be negative");
if (skip >= values.size()) {
return new DsonArray<>(0);
}
int endIndex = Math.min(values.size(), skip + count);
List dsonValues = values.subList(skip, endIndex);
return new DsonArray<>(dsonValues, ValuesPolicy.COPY, new DsonHeader<>());
}
@Override
public String toString() {
return "DsonArray{" +
"header=" + header +
", values=" + values +
'}';
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy