2 * Sone - PartContainer.java - Copyright © 2010–2016 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sone.text;
20 import java.util.ArrayDeque;
21 import java.util.ArrayList;
22 import java.util.Deque;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.NoSuchElementException;
26 import java.util.Objects;
28 import javax.annotation.Nonnull;
31 * Part implementation that can contain an arbitrary amount of other parts.
32 * Parts are added using the {@link #add(Part)} method and will be rendered in
33 * the order they are added.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class PartContainer implements Part, Iterable<Part> {
39 private final List<Part> parts = new ArrayList<Part>();
41 public void add(@Nonnull Part part) {
42 parts.add(Objects.requireNonNull(part));
46 public Part getPart(int index) {
47 return parts.get(index);
50 public void removePart(int index) {
60 public String getText() {
61 StringBuilder partText = new StringBuilder();
62 for (Part part : parts) {
63 partText.append(part.getText());
65 return partText.toString();
70 @SuppressWarnings("synthetic-access")
71 public Iterator<Part> iterator() {
72 return new Iterator<Part>() {
74 private Deque<Iterator<Part>> partStack = new ArrayDeque<Iterator<Part>>();
75 private Part nextPart;
76 private boolean foundNextPart;
77 private boolean noNextPart;
80 partStack.push(parts.iterator());
83 private void findNext() {
88 while (!partStack.isEmpty()) {
89 Iterator<Part> parts = partStack.pop();
90 if (parts.hasNext()) {
91 nextPart = parts.next();
92 partStack.push(parts);
93 if (nextPart instanceof PartContainer) {
94 partStack.push(((PartContainer) nextPart).iterator());
101 foundNextPart = true;
105 public boolean hasNext() {
114 throw new NoSuchElementException();
116 foundNextPart = false;
121 public void remove() {