

Namespace System

/*!
@brief  基本型の変換を行うクラス
*/

Class Convert
Public
	/*!
	@brief  文字列を32ビット符号付き値に変換する
	@author OverTaker
	@param  文字列
	@return 32ビット符号付き値
	*/
	Static Function ToInt32(value As String) As Long
		Return ToInt32(value, 10)
	End Function

	/*!
	@brief  文字列を任意の進数で32ビット符号付き値に変換する
	@author OverTaker
	@param  文字列
	@param  基数
	@return 32ビット符号付き値
	*/
	Static Function ToInt32(value As String, fromBase As Long) As Long
		Dim retVal As Long
		Dim negative = False As Boolean

		Dim init = 0 As Long
		While ActiveBasic.CType.IsSpace(value[init])
			init++
		Wend

		If Detail.IsMinus(value[init]) Then
			init++
			negative = True
		End If

		Dim i As Long
		Dim n As Long
		For i = init To ELM(value.Length)
			n = Detail.NumberFromChar(value[i])
			If n < fromBase Then
				retVal += n * fromBase^(ELM(value.Length) - i)
			Else
				Throw New ArgumentOutOfRangeException("System.Convert.ToInt32: The value was out of basevalue.", "value or fromBase")
			End If
		Next
		
		If negative Then
			Return -retVal
		Else
			Return retVal
		End If
	End Function
End Class

Namespace Detail
	/*!
	@brief  文字を値に変換する
	@author OverTaker
	@param  文字
	@return 値
	*/
	Function NumberFromChar(aCharacter As WCHAR) As Long
		If ActiveBasic.CType.IsDigit(aCharacter) Then
			Return aCharacter - &H30
		ElseIf ActiveBasic.CType.IsUpper(aCharacter) Then
			Return aCharacter - &H37
		ElseIf ActiveBasic.CType.IsLower(aCharacter) Then
			Return aCharacter - &H57
		Else
			Throw New ArgumentException("System.Convert.Detail: The character was invalid.", "aCharacter")
		End If
	End Function

	/*!
	@overload
	*/
	Function NumberFromChar(aCharacter As CHAR) As Long
		Return NumberFromChar(ActiveBasic.CType.Detail.Widen(aCharacter))
	End Function

	/*!
	@brief  文字が-記号かどうかを調べる
	@author OverTaker
	@param  文字
	@retval True  文字は-
	@retval Flase 文字は-でない
	*/
	Function IsMinus(aCharacter As WCHAR) As Boolean
		Return aCharacter = &H2D
	End Function

	/*!
	@overload
	*/
	Function IsMinus(aCharacter As CHAR) As Boolean
		Return IsMinus(ActiveBasic.CType.Detail.Widen(aCharacter))
	End Function
End Namespace

End Namespace