001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.hash;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020
021import java.io.FilterOutputStream;
022import java.io.IOException;
023import java.io.OutputStream;
024
025import javax.annotation.CheckReturnValue;
026
027/**
028 * An {@link OutputStream} that maintains a hash of the data written to it.
029 *
030 * @author Nick Piepmeier
031 * @since 16.0
032 */
033@Beta
034public final class HashingOutputStream extends FilterOutputStream {
035  private final Hasher hasher;
036
037  /**
038   * Creates an output stream that hashes using the given {@link HashFunction}, and forwards all
039   * data written to it to the underlying {@link OutputStream}.
040   *
041   * <p>The {@link OutputStream} should not be written to before or after the hand-off.
042   */
043  // TODO(user): Evaluate whether it makes sense to always piggyback the computation of a
044  // HashCode on an existing OutputStream, compared to creating a separate OutputStream that could
045  // be (optionally) be combined with another if needed (with something like
046  // MultiplexingOutputStream).
047  public HashingOutputStream(HashFunction hashFunction, OutputStream out) {
048    super(checkNotNull(out));
049    this.hasher = checkNotNull(hashFunction.newHasher());
050  }
051
052  @Override
053  public void write(int b) throws IOException {
054    hasher.putByte((byte) b);
055    out.write(b);
056  }
057
058  @Override
059  public void write(byte[] bytes, int off, int len) throws IOException {
060    hasher.putBytes(bytes, off, len);
061    out.write(bytes, off, len);
062  }
063
064  /**
065   * Returns the {@link HashCode} based on the data written to this stream. The result is
066   * unspecified if this method is called more than once on the same instance.
067   */
068  @CheckReturnValue
069  public HashCode hash() {
070    return hasher.hash();
071  }
072
073  // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior:
074  // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream.
075  // It should flush itself if necessary.
076  @Override
077  public void close() throws IOException {
078    out.close();
079  }
080}