/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * 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 SMethodsParser implements SParser
{
	private static SMethodsParser instance;

	private SMethodsParser()
	{
	}

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

		return instance;
	}

	public Object read(DataInputStream d) throws SClassFileException
	{
	    int i = -1;
	    int methodsCount;
	    SMethods methods;
	    SMethodInfo methodInfo;

	    methodsCount = SInputStream.
		readUnsignedShort(d, SConstants.ITEM_METHODS_COUNT);

	    methods = new SMethods(methodsCount);
	    
	    try {
		for (i = 0; i < methodsCount; i++) {
			methodInfo = (SMethodInfo)
				SMethodInfoParser.getInstance().read(d);
			methods.setMethod(i, methodInfo);
		}

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

	public void write(DataOutputStream d, Object obj)
		throws SClassFileException
	{
		SMethods methods = (SMethods) obj;
		int methodsCount = methods.count();

		SInputStream.writeShort(d, methodsCount);

		for (int i = 0; i < methodsCount; i++) {
			SMethodInfoParser.getInstance().write(
				d, methods.getMethod(i));
		}
	}
}
