|
| 1 | +/* |
| 2 | + * Copyright 2023 DiffPlug |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.diffplug.spotless.npm; |
| 17 | + |
| 18 | +import java.util.Arrays; |
| 19 | +import java.util.Iterator; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Objects; |
| 22 | + |
| 23 | +import javax.annotation.Nonnull; |
| 24 | + |
| 25 | +class ListableAdapter<T> implements Iterable<T> { |
| 26 | + |
| 27 | + private final List<T> delegate; |
| 28 | + |
| 29 | + @SuppressWarnings("unchecked") |
| 30 | + private ListableAdapter(Object delegate) { |
| 31 | + Objects.requireNonNull(delegate); |
| 32 | + if (!canAdapt(delegate)) { |
| 33 | + throw new IllegalArgumentException("Cannot create ListableAdapter from " + delegate.getClass() + ". Use canAdapt() to check first."); |
| 34 | + } |
| 35 | + if (delegate instanceof List) { |
| 36 | + this.delegate = (List<T>) delegate; |
| 37 | + } else if (delegate.getClass().isArray()) { |
| 38 | + this.delegate = Arrays.asList((T[]) delegate); |
| 39 | + } else { |
| 40 | + throw new IllegalArgumentException("Cannot create IterableAdapter from " + delegate.getClass()); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + static <T> Iterable<T> adapt(Object delegate) { |
| 45 | + return new ListableAdapter<>(delegate); |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + @Nonnull |
| 50 | + public Iterator<T> iterator() { |
| 51 | + return delegate.iterator(); |
| 52 | + } |
| 53 | + |
| 54 | + static boolean canAdapt(Object delegate) { |
| 55 | + Objects.requireNonNull(delegate); |
| 56 | + return delegate instanceof List || delegate.getClass().isArray(); |
| 57 | + } |
| 58 | +} |
0 commit comments