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