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