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; 020import java.io.FilterOutputStream; 021import java.io.IOException; 022import java.io.OutputStream; 023 024/** 025 * An {@link OutputStream} that maintains a hash of the data written to it. 026 * 027 * @author Zoe Piepmeier 028 * @since 16.0 029 */ 030@Beta 031@ElementTypesAreNonnullByDefault 032public final class HashingOutputStream extends FilterOutputStream { 033 private final Hasher hasher; 034 035 /** 036 * Creates an output stream that hashes using the given {@link HashFunction}, and forwards all 037 * data written to it to the underlying {@link OutputStream}. 038 * 039 * <p>The {@link OutputStream} should not be written to before or after the hand-off. 040 */ 041 // TODO(user): Evaluate whether it makes sense to always piggyback the computation of a 042 // HashCode on an existing OutputStream, compared to creating a separate OutputStream that could 043 // be (optionally) be combined with another if needed (with something like 044 // MultiplexingOutputStream). 045 public HashingOutputStream(HashFunction hashFunction, OutputStream out) { 046 super(checkNotNull(out)); 047 this.hasher = checkNotNull(hashFunction.newHasher()); 048 } 049 050 @Override 051 public void write(int b) throws IOException { 052 hasher.putByte((byte) b); 053 out.write(b); 054 } 055 056 @Override 057 public void write(byte[] bytes, int off, int len) throws IOException { 058 hasher.putBytes(bytes, off, len); 059 out.write(bytes, off, len); 060 } 061 062 /** 063 * Returns the {@link HashCode} based on the data written to this stream. The result is 064 * unspecified if this method is called more than once on the same instance. 065 */ 066 public HashCode hash() { 067 return hasher.hash(); 068 } 069 070 // Overriding close() because FilterOutputStream's close() method pre-JDK8 has bad behavior: 071 // it silently ignores any exception thrown by flush(). Instead, just close the delegate stream. 072 // It should flush itself if necessary. 073 @Override 074 public void close() throws IOException { 075 out.close(); 076 } 077}