org.conqat.lib.commons.io.LimitedWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
/*
* Copyright (c) CQSE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.conqat.lib.commons.io;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.io.Writer;
/**
* A {@link Writer} that delegates to another {@link Writer} until a given maximum number of
* characters has been written. It then writes a final ellipsis and stops delegating.
*/
public class LimitedWriter extends Writer {
private final Writer delegate;
/**
* The number of remaining characters that can still be {@linkplain #write(char[], int, int)
* written} until the limit is reached. A value of {@code -1} denotes the fact the final ellipsis
* has already been written to the {@link #delegate}.
*/
private int charsRemaining;
public LimitedWriter(Writer delegate, int maxChars) {
if (maxChars < 0) {
throw new IllegalArgumentException("Negative number of maximum characters");
}
this.delegate = requireNonNull(delegate);
this.charsRemaining = maxChars;
}
@Override
public void write(char[] buffer, int offset, int length) throws IOException {
if (charsRemaining >= length) {
delegate.write(buffer, offset, length);
charsRemaining -= length;
} else if (charsRemaining >= 0) {
delegate.write(buffer, offset, charsRemaining);
delegate.write("[...]");
charsRemaining = -1;
}
}
@Override
public void flush() throws IOException {
delegate.flush();
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public String toString() {
return delegate.toString();
}
}