001: /*
002: * @(#)Counter.java 1.2 04/12/06
003: *
004: * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package org.pnuts.lib;
010:
011: import pnuts.lang.*;
012: import pnuts.lang.Runtime;
013: import java.io.*;
014: import java.util.*;
015:
016: class Counter {
017:
018: public Number count(Object a, Context context) {
019: if (a instanceof Enumeration) {
020: Enumeration e = (Enumeration) a;
021: int c = 0;
022: while (e.hasMoreElements()) {
023: c++;
024: e.nextElement();
025: }
026: return new Integer(c);
027: } else if (a instanceof Iterator) {
028: Iterator it = (Iterator) a;
029: int c = 0;
030: while (it.hasNext()) {
031: c++;
032: it.next();
033: }
034: return new Integer(c);
035: } else if (a instanceof Generator) {
036: Generator g = (Generator) a;
037: class F extends PnutsFunction {
038: int count = 0;
039:
040: protected Object exec(Object[] args, Context context) {
041: count++;
042: return null;
043: }
044: }
045: F f = new F();
046: g.apply(f, context);
047: return new Integer(f.count);
048: } else if (a instanceof InputStream) {
049: byte[] buf = new byte[4096];
050: int n = 0;
051: int c = 0;
052: InputStream in = (InputStream) a;
053: try {
054: while ((n = in.read(buf)) != -1) {
055: c += n;
056: }
057: } catch (IOException e) {
058: throw new PnutsException(e, context);
059: }
060: return new Integer(c);
061: } else if (a instanceof Reader) {
062: char[] buf = new char[4096];
063: int n = 0;
064: int c = 0;
065: Reader in = (Reader) a;
066: try {
067: while ((n = in.read(buf)) != -1) {
068: c += n;
069: }
070: } catch (IOException e) {
071: throw new PnutsException(e, context);
072: }
073: return new Integer(c);
074: } else {
075: return size(a, context);
076: }
077: }
078:
079: public Number size(Object a, Context context) {
080: if (a == null) {
081: return new Integer(0);
082: } else if (a instanceof String) {
083: return new Integer(((String) a).length());
084: } else if (a instanceof StringBuffer) {
085: return new Integer(((StringBuffer) a).length());
086: } else if (a instanceof Object[]) {
087: return new Integer(((Object[]) a).length);
088: } else if (a instanceof File) {
089: return new Long(((File) a).length());
090: } else if (a instanceof Collection) {
091: return new Integer(((Collection) a).size());
092: } else if (a instanceof Map) {
093: return new Integer(((Map) a).size());
094: } else if (Runtime.isArray(a)) {
095: return new Integer(Runtime.getArrayLength(a));
096: } else {
097: throw new IllegalArgumentException(String.valueOf(a));
098: }
099: }
100: }
|