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 025/** 026 * An {@link OutputStream} that maintains a hash of the data written to it. 027 * 028 * @author Nick Piepmeier 029 * @since 16.0 030 */ 031@Beta 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 public void write(int b) throws IOException { 051 hasher.putByte((byte) b); 052 out.write(b); 053 } 054 055 @Override public void write(byte[] bytes, int off, int len) throws IOException { 056 hasher.putBytes(bytes, off, len); 057 out.write(bytes, off, len); 058 } 059 060 /** 061 * Returns the {@link HashCode} based on the data written to this stream. The result is 062 * unspecified if this method is called more than once on the same instance. 063 */ 064 public HashCode hash() { 065 return hasher.hash(); 066 } 067}