001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.common.util;
017
018import java.io.IOException;
019import java.io.Reader;
020import java.util.concurrent.atomic.AtomicLong;
021
022/**
023 * An {@link Reader} implementation that can wrap another input stream and determine the number of bytes read.
024 */
025public class SizeMeasuringReader extends Reader {
026    private final Reader stream;
027    private final AtomicLong size;
028
029    public SizeMeasuringReader( Reader Reader,
030                                AtomicLong size ) {
031        this.stream = Reader;
032        this.size = size;
033    }
034
035    @Override
036    public int read( char[] cbuf,
037                     int off,
038                     int len ) throws IOException {
039        // Read from the stream ...
040        int n = stream.read(cbuf, off, len);
041        if (n != -1) {
042            size.addAndGet(n);
043        }
044        return n;
045    }
046
047    @Override
048    public int read() throws IOException {
049        int result = stream.read();
050        if (result != -1) {
051            size.addAndGet(1);
052        }
053        return result;
054    }
055
056    @Override
057    public synchronized void mark( int readlimit ) throws IOException {
058        stream.mark(readlimit);
059    }
060
061    @Override
062    public boolean markSupported() {
063        return stream.markSupported();
064    }
065
066    @Override
067    public synchronized void reset() throws IOException {
068        stream.reset();
069    }
070
071    @Override
072    public void close() throws IOException {
073        stream.close();
074    }
075}