ProtoList.java
/*
* Copyright 2022 Proto Utils Authors
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 net.morimekta.proto;
import com.google.protobuf.Descriptors;
import com.google.protobuf.MessageOrBuilder;
import net.morimekta.proto.utils.ValueUtil;
import java.util.AbstractList;
import java.util.RandomAccess;
import static java.util.Objects.requireNonNull;
/**
* A list wrapping a repeated proto field. This is an unmodifiable list.
*
* @param <T> The item type.
*/
public class ProtoList<T>
extends AbstractList<T>
implements RandomAccess {
private transient final MessageOrBuilder message;
private transient final Descriptors.FieldDescriptor field;
/**
* @param message Message the field is on.
* @param field The repeated field.
*/
public ProtoList(MessageOrBuilder message, Descriptors.FieldDescriptor field) {
requireNonNull(message, "message == null");
requireNonNull(field, "field == null");
if (!field.isRepeated() || field.isMapField()) {
throw new IllegalArgumentException("Not a list type: " + field);
}
this.message = message;
this.field = field;
}
@Override
public int size() {
return message.getRepeatedFieldCount(field);
}
@Override
@SuppressWarnings("unchecked")
public T get(int i) {
return (T) ValueUtil.toJavaValue(field, message.getRepeatedField(field, i));
}
@Override
public String toString() {
return ValueUtil.asString(this);
}
}