feat(serialize): add convenience method for copying an element from a reader to a writer

This commit is contained in:
Johannes Frohnmeyer 2024-04-13 20:47:04 +02:00
parent b7ef2741b3
commit f03763f86d
Signed by: Johannes
GPG Key ID: E76429612C2929F4
1 changed files with 41 additions and 0 deletions

View File

@ -64,6 +64,47 @@ public abstract class SerializeReader<TEx extends Throwable, T extends Serialize
public abstract String getPath();
public abstract String getPreviousPath();
/**
* Copies the current element to the writer.
*
* @param writer the writer to copy to
* @throws TEx if an error occurs
*/
public void copyTo(SerializeWriter<TEx, ?> writer) throws TEx {
switch (peek()) {
case BEGIN_ARRAY -> {
this.beginArray();
writer.beginArray();
while (this.hasNext()) {
this.copyTo(writer);
}
this.endArray();
writer.endArray();
}
case END_ARRAY -> throw new IllegalStateException("Cannot copy standalone END_ARRAY");
case BEGIN_OBJECT -> {
this.beginObject();
writer.beginObject();
while (this.hasNext()) {
writer.name(this.nextName());
this.copyTo(writer);
}
this.endObject();
writer.endObject();
}
case END_OBJECT -> throw new IllegalStateException("Cannot copy standalone END_OBJECT");
case NAME -> throw new IllegalStateException("Cannot copy standalone NAME");
case STRING -> writer.value(this.nextString());
case NUMBER -> writer.value(this.nextNumber());
case BOOLEAN -> writer.value(this.nextBoolean());
case NULL -> {
this.nextNull();
writer.nullValue();
}
case END_DOCUMENT -> throw new IllegalStateException("Cannot copy END_DOCUMENT");
}
}
@Override
public String toString() {
return getClass().getSimpleName() + locationString();