2 * Sone - PartContainer.java - Copyright © 2010 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.io.IOException;
21 import java.io.StringWriter;
22 import java.io.Writer;
23 import java.util.ArrayDeque;
24 import java.util.ArrayList;
25 import java.util.Deque;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.NoSuchElementException;
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 Iterable<Part> {
39 /** The parts to render. */
40 private final List<Part> parts = new ArrayList<Part>();
47 * Adds a part to render.
52 public void add(Part part) {
57 * Returns the part at the given index.
60 * The index of the part
63 public Part getPart(int index) {
64 return parts.get(index);
68 * Removes the part at the given index.
71 * The index of the part to remove
73 public void removePart(int index) {
78 * Returns the number of parts.
80 * @return The number of parts
94 @SuppressWarnings("synthetic-access")
95 public Iterator<Part> iterator() {
96 return new Iterator<Part>() {
98 private Deque<Iterator<Part>> partStack = new ArrayDeque<Iterator<Part>>();
99 private Part nextPart;
100 private boolean foundNextPart;
101 private boolean noNextPart;
104 partStack.push(parts.iterator());
107 private void findNext() {
112 while (!partStack.isEmpty()) {
113 Iterator<Part> parts = partStack.pop();
114 if (parts.hasNext()) {
115 nextPart = parts.next();
116 partStack.push(parts);
117 if (nextPart instanceof PartContainer) {
118 partStack.push(((PartContainer) nextPart).iterator());
125 foundNextPart = true;
129 public boolean hasNext() {
138 throw new NoSuchElementException();
140 foundNextPart = false;
145 public void remove() {