package tcra.math;

/**
 * MathIntegerParser is used to parse a MathInteger out of a String.
 * If a valid integer can not be parsed, a MathFormatException is
 * thrown. MathIntegerPaser follows the Singleton pattern since it
 * is stateless and can save memory by only allowing one instance to
 * exist.
 */
public class MathIntegerParser extends MathTypeParser
{   
    /**
    * Consumes all the characters from the front of a StringBuilder
    * until it finds a ',' or '>'.  Then Integer is used to convert
    * the String into an integer.
    *
    * @param input StringBuilder that contains an integer at the
    *              front.
    * @return      MathInteger containing the integer value parsed
    *              and a reference to this MathIntegerParser.
    * @throws MathFormatException If what is read is not a valid
    *                             integer.
    */
   public MathInteger parse(StringBuilder input)
          throws MathFormatException
   {
      eatWhitespace(input);
      StringBuilder int_rep = new StringBuilder("");

      while(input.length() > 0 && Character.isDigit(input.charAt(0)))
      {
         int_rep.append(input.charAt(0));
         input.deleteCharAt(0); // destructive parse
      } // end while

      // Empty element
      if(int_rep.toString().equals("")) return null;

      int val;
      try
      {
         // convert using Integer's static parseInt method
         val = Integer.parseInt(int_rep.toString());
      } // end try
      catch(Exception e)
      {
         throw new MathFormatException(e);
      } // end catch(Exception)
      return new MathInteger(val);
   } // end parse(StringBUilder)
} // end class
