/**
 * <p>
 * (C) Siemens Aktiengesellschaft, Germany, 2015
 * </p>
 *
 * <p>created 04.02.2015 - 19:03:27</p>
 * 
 * @since	Sol7
 * @author  zelgerpe
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program (see the file LICENSE.txt for more
 * details); if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 */

package org.acplt.oncrpc;

import java.io.IOException;

/**
 * <p>
 * Title: common - XdrHashCode provides ...
 * </p>
 * <p>
 * Description:
 * calculate HashCode by using {@link XdrAble#xdrEncode(XdrEncodingStream)}
 * <pre>
    @Override
    public int hashCode()
    {
      XdrHashCode xhc=new XdrHashCode();
      try
      {
        this.xdrEncode(xhc);
        return xhc.getResult();
      }
      catch (OncRpcException | IOException e)
      {
        return 42;
      }
    }
 * </pre>
 * </p>
 */
public class XdrHashCode extends XdrEncodingStream
{
  static final int prime=31;
  protected int result=31;
  @Override
  public void xdrEncodeInt(int value) throws OncRpcException, IOException
  {
    result = prime * result + value;
  }

  @Override
  public void xdrEncodeOpaque(byte[] value, int offset, int length) throws OncRpcException, IOException
  {
    for(int i=offset; i<length; i++)
      result = prime * result + value[i];
  }
  
  public int getResult()
  {
    return result;
  }
  
  public static int hashCode(XdrAble xa)
  {
    XdrHashCode xhc=new XdrHashCode();    
    try
    {
      xa.xdrEncode(xhc);
      return xhc.result;
    }
    catch (OncRpcException | IOException e)
    {
      return 42;
    }    
  }
}
