/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * This source file is part of SableVM.                            *
 *                                                                 *
 * See the file "LICENSE" for the copyright information and for    *
 * the terms and conditions for copying, distribution and          *
 * modification of this source file.                               *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/**
 * @author Patrick Latifi
 */
import java.io.*;

class SLocalVariablesParser implements SParser
{
	private static SLocalVariablesParser instance;

	private SLocalVariablesParser()
	{
	}

	public static SLocalVariablesParser getInstance()
	{
		if (instance == null)
			instance = new SLocalVariablesParser();

		return instance;
	}

	public Object read(DataInputStream d) throws SClassFileException
	{
		int i = -1;
		int tableLength;
		SLocalVariables variables;
	    
		tableLength = SInputStream.readUnsignedShort(
			d, SConstants.ITEM_LOCAL_VARIABLE_TABLE_LENGTH);

		variables = new SLocalVariables(tableLength);
		try {
			for (i = 0; i < tableLength; i++) {

				SLocalVariableTableEntry tableEntry =
					(SLocalVariableTableEntry)
					SLocalVariableTableEntryParser.
					getInstance().read(d);
		    
				variables.setLocalVariableTableEntry(
					i, tableEntry);
			}

			return variables;
		}
		catch(SClassFileException cfe) {
			throw new SClassFileException(
				SExceptionMessages.
				PARSING_GENERIC_AT_INDEX_MESSAGE +
				i + "\n" + cfe.getMessage());
		}
	}

	public void write(DataOutputStream d, Object obj)
		throws SClassFileException
	{
		SLocalVariables variables = (SLocalVariables) obj;
		int tableLength = variables.count();

		SInputStream.writeShort(d, tableLength);
		for (int i = 0; i < tableLength; i++) {
			SLocalVariableTableEntryParser.getInstance().write(
				d, variables.getLocalVariableTableEntry(i));
		}
	}
}
