/*
 * Copyright 2009-2010 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.lisp.nano.util;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2012/01/10
 */
public final class Utils {

	//
	private Utils() {}

	/**
	 * returns string representation of hash code
	 * of the given object.
	 * <p>与えられたオブジェクトのハッシュ値の文字列表現を得ます。
	 * 
	 * @return string representation of hash code
	 */
	public static String printHash(Object o) {
		return (o == null) ? "0" : Integer.toString(o.hashCode(), 16);
	}

	/**
	 * Transform an object to its string representation:
	 * If the object is null, returns an empty string.<br>
	 * <p>与えられたオブジェクトの文字列表現を返す.オブジェクトがnullの
	 * ときは空文字列を返す.
	 * 
	 * @param attr  an object to transform
	 * @return  string representation
	 * @see  java.lang.Object
	 */
	public static /*inline*/ String toString(Object attr) {
		return (attr == null) ? "" : attr.toString();
	}

	/**
	 * calculates the G.C.D. of the given values.
	 * <p>与えられた数の最大公約数を得る。
	 * 
	 * @param v1 value to be calculated 
	 * @param v2 another value to be calculated
	 * @return G.C.D. of the given values
	 */
	public static int gcd(int v1, int v2) {
		int x = (v1 < 0) ? -v1 : v1;
		int y = (v2 < 0) ? -v2 : v2;
		
		if(x == 0 && y == 0) {
			return 0;
		} else {
			while(y != 0) {
				int t = x % y;
				
				x = y;
				y = t;
			}
			return x;
		}
	}

	/**
	 * returns 1 when the given value is positive,
	 * returns -1 when the value is negative,
	 * otherwise returns 0.
	 * <p>与えられた値が正のとき1を、負のとき-1を、
	 * それ以外のときは0を得る。
	 * 
	 * @param value value to be tested
	 */
	public static int signum(int value) {
		return (value > 0) ? 1 : (value < 0) ? -1 : 0;
	}

}
