Skip to content

Commit

Permalink
StringCollectionProperty: support for Iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
hohwille committed Jun 23, 2024
1 parent bce2ff5 commit 7aceb0a
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
package io.github.mmm.property.string;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;

import io.github.mmm.base.collection.AbstractIterator;
import io.github.mmm.marshall.StructuredReader;
import io.github.mmm.marshall.StructuredWriter;
import io.github.mmm.property.PropertyMetadata;
Expand All @@ -22,7 +25,7 @@
*
* @since 1.0.0
*/
public abstract class StringCollectionProperty extends StringProperty {
public abstract class StringCollectionProperty extends StringProperty implements Iterable<String> {

/**
* The constructor.
Expand Down Expand Up @@ -504,4 +507,56 @@ public void write(StructuredWriter writer) {
writer.writeEnd();
}

@Override
public Iterator<String> iterator() {

String value = get();
if (value == null) {
return Collections.emptyIterator();
}
return new ValueIterator(value, getSeparator(), isEncloseWithSeparator());
}

private static class ValueIterator extends AbstractIterator<String> {

private final String string;

private final String separator;

private final int end;

private int index = 0;

private ValueIterator(String string, String separator, boolean enclose) {

super();
this.string = string;
this.separator = separator;
this.end = string.length();
if (enclose && string.startsWith(separator)) {
this.index = separator.length();
}
findFirst();
}

@Override
protected String findNext() {

if (this.index >= this.end) {
return null;
}
int i = this.string.indexOf(this.separator, this.index);
if (i < 0) {
i = this.end;
}
String result = this.string.substring(this.index, i);
this.index = i + this.separator.length();
if (this.index >= this.end) {
this.index = this.end;
}
return result;
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -295,4 +295,20 @@ public void testWriteArray() {
assertThat(json).isEqualTo("[\"hit\",\"pop\",\"partyhit\",\"superhits\"]");
}

/**
* Test {@link StringCollectionProperty#iterator()} after multiple elements have been added.
*/
@Test
public void testIterable() {

// arrange
StringCollectionProperty property = createEmpty();
// act
property.add("one");
property.add("two");
property.add("three");
// assert
Iterable<String> iterable = property;
assertThat(iterable).containsExactly("one", "two", "three");
}
}

0 comments on commit 7aceb0a

Please sign in to comment.