add logging of PC92A ip addresses
[spider.git] / spider-web / Format.java
1 /*
2  * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM)
3  * Published By SunSoft Press/Prentice-Hall
4  * Copyright (C) 1996 Sun Microsystems Inc.
5  * All Rights Reserved. ISBN 0-13-565755-5
6  *
7  * Permission to use, copy, modify, and distribute this 
8  * software and its documentation for NON-COMMERCIAL purposes
9  * and without fee is hereby granted provided that this 
10  * copyright notice appears in all copies. 
11  * 
12  * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR 
13  * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 
14  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
15  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
16  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
17  * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED 
18  * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING 
19  * THIS SOFTWARE OR ITS DERIVATIVES.
20  */
21  
22 /**
23  * A class for formatting numbers that follows printf conventions.
24  * Also implements C-like atoi and atof functions
25  * @version 1.01 15 Feb 1996 
26  * @author Cay Horstmann
27  */
28
29
30
31 import java.io.*;
32
33 public class Format
34
35 { /** 
36   * Formats the number following printf conventions.
37   * Main limitation: Can only handle one format parameter at a time
38   * Use multiple Format objects to format more than one number
39   * @param s the format string following printf conventions
40   * The string has a prefix, a format code and a suffix. The prefix and suffix
41   * become part of the formatted output. The format code directs the
42   * formatting of the (single) parameter to be formatted. The code has the
43   * following structure
44   * <ul>
45   * <li> a % (required)
46   * <li> a modifier (optional)
47   * <dl>
48   * <dt> + <dd> forces display of + for positive numbers
49   * <dt> 0 <dd> show leading zeroes
50   * <dt> - <dd> align left in the field
51   * <dt> space <dd> prepend a space in front of positive numbers
52   * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
53   * </dl>
54   * <li> an integer denoting field width (optional)
55   * <li> a period followed by an integer denoting precision (optional)
56   * <li> a format descriptor (required)
57   * <dl>
58   * <dt>f <dd> floating point number in fixed format
59   * <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
60   * <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
61   * <dt>d, i <dd> integer in decimal
62   * <dt>x <dd> integer in hexadecimal
63   * <dt>o <dd> integer in octal
64   * <dt>s <dd> string
65   * <dt>c <dd> character
66   * </dl>
67   * </ul>
68   * @exception IllegalArgumentException if bad format
69   */
70
71    public Format(String s)
72    {  width = 0;
73       precision = -1;
74       pre = "";
75       post = "";
76       leading_zeroes = false;
77       show_plus = false;
78       alternate = false;
79       show_space = false;
80       left_align = false;
81       fmt = ' '; 
82       
83       int state = 0; 
84       int length = s.length();
85       int parse_state = 0; 
86       // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
87       // 4 = format, 5 = end
88       int i = 0;
89       
90       while (parse_state == 0)
91       {  if (i >= length) parse_state = 5;
92          else if (s.charAt(i) == '%')
93          {  if (i < length - 1)
94             {  if (s.charAt(i + 1) == '%')
95                {  pre = pre + '%';
96                   i++;
97                }
98                else
99                   parse_state = 1;
100             }
101             else throw new java.lang.IllegalArgumentException();
102          }
103          else
104             pre = pre + s.charAt(i);
105          i++;
106       }
107       while (parse_state == 1)
108       {  if (i >= length) parse_state = 5;
109          else if (s.charAt(i) == ' ') show_space = true;
110          else if (s.charAt(i) == '-') left_align = true; 
111          else if (s.charAt(i) == '+') show_plus = true;
112          else if (s.charAt(i) == '0') leading_zeroes = true;
113          else if (s.charAt(i) == '#') alternate = true;
114          
115          
116          else { parse_state = 2; i--; }
117          i++;
118       }      
119       while (parse_state == 2)
120       {  if (i >= length) parse_state = 5;
121          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
122          {  width = width * 10 + s.charAt(i) - '0';
123             i++;
124          }
125          else if (s.charAt(i) == '.')
126          {  parse_state = 3;
127             precision = 0;
128             i++;
129          }
130          else 
131             parse_state = 4;            
132       }
133       while (parse_state == 3)
134       {  if (i >= length) parse_state = 5;
135          else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
136          {  precision = precision * 10 + s.charAt(i) - '0';
137             i++;
138          }
139          else 
140             parse_state = 4;                  
141       }
142       if (parse_state == 4) 
143       {  if (i >= length) parse_state = 5;
144          else fmt = s.charAt(i);
145          i++;
146       }
147       if (i < length)
148          post = s.substring(i, length);
149    }      
150
151   /** 
152   * prints a formatted number following printf conventions
153   * @param s a PrintStream
154   * @param fmt the format string
155   * @param x the double to print
156   */
157   
158    public static void print(java.io.PrintStream s, String fmt, double x)
159    {  s.print(new Format(fmt).form(x));
160    }
161
162   /** 
163   * prints a formatted number following printf conventions
164   * @param s a PrintStream
165   * @param fmt the format string
166   * @param x the long to print
167   */
168   public static void print(java.io.PrintStream s, String fmt, long x)
169    {  s.print(new Format(fmt).form(x));
170    }
171
172   /** 
173   * prints a formatted number following printf conventions
174   * @param s a PrintStream
175   * @param fmt the format string
176   * @param x the character to 
177   */
178   
179    public static void print(java.io.PrintStream s, String fmt, char x)
180    {  s.print(new Format(fmt).form(x));
181    }
182
183   /** 
184   * prints a formatted number following printf conventions
185   * @param s a PrintStream, fmt the format string
186   * @param x a string that represents the digits to print
187   */
188   
189    public static void print(java.io.PrintStream s, String fmt, String x)
190    {  s.print(new Format(fmt).form(x));
191    }
192    
193   /** 
194   * Converts a string of digits (decimal, octal or hex) to an integer
195   * @param s a string
196   * @return the numeric value of the prefix of s representing a base 10 integer
197   */
198   
199    public static int atoi(String s)
200    {  return (int)atol(s);
201    } 
202    
203   /** 
204   * Converts a string of digits (decimal, octal or hex) to a long integer
205   * @param s a string
206   * @return the numeric value of the prefix of s representing a base 10 integer
207   */
208   
209    public static long atol(String s)
210    {  int i = 0;
211
212       while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
213       if (i < s.length() && s.charAt(i) == '0')
214       {  if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
215             return parseLong(s.substring(i + 2), 16);
216          else return parseLong(s, 8);
217       }
218       else return parseLong(s, 10);
219    }
220
221    private static long parseLong(String s, int base)
222    {  int i = 0;
223       int sign = 1;
224       long r = 0;
225       
226       while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
227       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
228       else if (i < s.length() && s.charAt(i) == '+') { i++; }
229       while (i < s.length())
230       {  char ch = s.charAt(i);
231          if ('0' <= ch && ch < '0' + base)
232             r = r * base + ch - '0';
233          else if ('A' <= ch && ch < 'A' + base - 10)
234             r = r * base + ch - 'A' + 10 ;
235          else if ('a' <= ch && ch < 'a' + base - 10)
236             r = r * base + ch - 'a' + 10 ;
237          else 
238             return r * sign;
239          i++;
240       }
241       return r * sign;      
242    }
243       
244    /** 
245    * Converts a string of digits to an double
246    * @param s a string
247    */
248    
249    public static double atof(String s)
250    {  int i = 0;
251       int sign = 1;
252       double r = 0; // integer part
253       double f = 0; // fractional part
254       double p = 1; // exponent of fractional part
255       int state = 0; // 0 = int part, 1 = frac part
256       
257       while (i < s.length() && Character.isSpace(s.charAt(i))) i++;
258       if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
259       else if (i < s.length() && s.charAt(i) == '+') { i++; }
260       while (i < s.length())
261       {  char ch = s.charAt(i);
262          if ('0' <= ch && ch <= '9')
263          {  if (state == 0)
264                r = r * 10 + ch - '0';
265             else if (state == 1)
266             {  p = p / 10;
267                r = r + p * (ch - '0');
268             }
269          }
270          else if (ch == '.') 
271          {  if (state == 0) state = 1; 
272             else return sign * r;
273          }
274          else if (ch == 'e' || ch == 'E')
275          {  long e = (int)parseLong(s.substring(i + 1), 10);
276             return sign * r * Math.pow(10, e);
277          }
278          else return sign * r;
279          i++;
280       }
281       return sign * r;
282    }
283             
284    /** 
285    * Formats a double into a string (like sprintf in C)
286    * @param x the number to format
287    * @return the formatted string 
288    * @exception IllegalArgumentException if bad argument
289    */
290    
291    public String form(double x)
292    {  String r;
293       if (precision < 0) precision = 6;
294       int s = 1;
295       if (x < 0) { x = -x; s = -1; }
296       if (fmt == 'f')
297          r = fixed_format(x);
298       else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
299          r = exp_format(x);
300       else throw new java.lang.IllegalArgumentException();
301       
302       return pad(sign(s, r));
303    }
304    
305    /** 
306    * Formats a long integer into a string (like sprintf in C)
307    * @param x the number to format
308    * @return the formatted string 
309    */
310    
311    public String form(long x)
312    {  String r; 
313       int s = 0;
314       if (fmt == 'd' || fmt == 'i')
315       {  s = 1;
316          if (x < 0) { x = -x; s = -1; }
317          r = "" + x;
318       }
319       else if (fmt == 'o')
320          r = convert(x, 3, 7, "01234567");
321       else if (fmt == 'x')
322          r = convert(x, 4, 15, "0123456789abcdef");
323       else if (fmt == 'X')
324          r = convert(x, 4, 15, "0123456789ABCDEF");
325       else throw new java.lang.IllegalArgumentException();
326          
327       return pad(sign(s, r));
328    }
329    
330    /** 
331    * Formats a character into a string (like sprintf in C)
332    * @param x the value to format
333    * @return the formatted string 
334    */
335    
336    public String form(char c)
337    {  if (fmt != 'c')
338          throw new java.lang.IllegalArgumentException();
339
340       String r = "" + c;
341       return pad(r);
342    }
343    
344    /** 
345    * Formats a string into a larger string (like sprintf in C)
346    * @param x the value to format
347    * @return the formatted string 
348    */
349    
350    public String form(String s)
351    {  if (fmt != 's')
352          throw new java.lang.IllegalArgumentException();
353       if (precision >= 0) s = s.substring(0, precision);
354       return pad(s);
355    }
356    
357     
358    /**
359    * a test stub for the format class
360    */
361    
362    public static void main(String[] a)
363    {  double x = 1.23456789012;
364       double y = 123;
365       double z = 1.2345e30;
366       double w = 1.02;
367       double u = 1.234e-5;
368       int d = 0xCAFE;
369       Format.print(System.out, "x = |%f|\n", x);
370       Format.print(System.out, "u = |%20f|\n", u);
371       Format.print(System.out, "x = |% .5f|\n", x);
372       Format.print(System.out, "w = |%20.5f|\n", w);
373       Format.print(System.out, "x = |%020.5f|\n", x);
374       Format.print(System.out, "x = |%+20.5f|\n", x);
375       Format.print(System.out, "x = |%+020.5f|\n", x);
376       Format.print(System.out, "x = |% 020.5f|\n", x);
377       Format.print(System.out, "y = |%#+20.5f|\n", y);
378       Format.print(System.out, "y = |%-+20.5f|\n", y);
379       Format.print(System.out, "z = |%20.5f|\n", z);
380       
381       Format.print(System.out, "x = |%e|\n", x);
382       Format.print(System.out, "u = |%20e|\n", u);
383       Format.print(System.out, "x = |% .5e|\n", x);
384       Format.print(System.out, "w = |%20.5e|\n", w);
385       Format.print(System.out, "x = |%020.5e|\n", x);
386       Format.print(System.out, "x = |%+20.5e|\n", x);
387       Format.print(System.out, "x = |%+020.5e|\n", x);
388       Format.print(System.out, "x = |% 020.5e|\n", x);
389       Format.print(System.out, "y = |%#+20.5e|\n", y);
390       Format.print(System.out, "y = |%-+20.5e|\n", y);
391       
392       Format.print(System.out, "x = |%g|\n", x);
393       Format.print(System.out, "z = |%g|\n", z);
394       Format.print(System.out, "w = |%g|\n", w);
395       Format.print(System.out, "u = |%g|\n", u);
396       Format.print(System.out, "y = |%.2g|\n", y);
397       Format.print(System.out, "y = |%#.2g|\n", y);
398
399       Format.print(System.out, "d = |%d|\n", d);
400       Format.print(System.out, "d = |%20d|\n", d);            
401       Format.print(System.out, "d = |%020d|\n", d);    
402       Format.print(System.out, "d = |%+20d|\n", d);
403       Format.print(System.out, "d = |% 020d|\n", d);
404       Format.print(System.out, "d = |%-20d|\n", d);
405       Format.print(System.out, "d = |%20.8d|\n", d);
406       Format.print(System.out, "d = |%x|\n", d);            
407       Format.print(System.out, "d = |%20X|\n", d);    
408       Format.print(System.out, "d = |%#20x|\n", d);
409       Format.print(System.out, "d = |%020X|\n", d);
410       Format.print(System.out, "d = |%20.8x|\n", d);
411       Format.print(System.out, "d = |%o|\n", d);            
412       Format.print(System.out, "d = |%020o|\n", d);    
413       Format.print(System.out, "d = |%#20o|\n", d);
414       Format.print(System.out, "d = |%#020o|\n", d);
415       Format.print(System.out, "d = |%20.12o|\n", d);
416       
417       Format.print(System.out, "s = |%-20s|\n", "Hello");      
418       Format.print(System.out, "s = |%-20c|\n", '!');      
419    }
420
421    
422    private static String repeat(char c, int n)
423    {  if (n <= 0) return "";
424       StringBuffer s = new StringBuffer(n);
425       for (int i = 0; i < n; i++) s.append(c);
426       return s.toString();
427    }
428
429    private static String convert(long x, int n, int m, String d)
430    {  if (x == 0) return "0";
431       String r = "";
432       while (x != 0)
433       {  r = d.charAt((int)(x & m)) + r;
434          x = x >>> n;
435       }
436       return r;
437    }
438
439    private String pad(String r)
440    {  String p = repeat(' ', width - r.length());
441       if (left_align) return pre + r + p + post;
442       else return pre + p + r + post;
443    }
444    
445    private String sign(int s, String r)
446    {  String p = "";
447       if (s < 0) p = "-"; 
448       else if (s > 0)
449       {  if (show_plus) p = "+";
450          else if (show_space) p = " ";
451       }
452       else
453       {  if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
454          else if (fmt == 'x' && alternate) p = "0x";
455          else if (fmt == 'X' && alternate) p = "0X";
456       }
457       int w = 0;
458       if (leading_zeroes) 
459          w = width;
460       else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') 
461          && precision > 0) w = precision;
462       
463       return p + repeat('0', w - p.length() - r.length()) + r;
464    }
465    
466            
467    private String fixed_format(double d)
468    {  String f = "";
469
470       if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);
471    
472       long l = (long)(precision == 0 ? d + 0.5 : d);
473       f = f + l;
474       
475       double fr = d - l; // fractional part
476       if (fr >= 1 || fr < 0) return exp_format(d);
477     
478       return f + frac_part(fr);
479    }   
480    
481    private String frac_part(double fr)
482    // precondition: 0 <= fr < 1
483    {  String z = "";
484       if (precision > 0)
485       {  double factor = 1;
486          String leading_zeroes = "";
487          for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) 
488          {  factor *= 10; 
489             leading_zeroes = leading_zeroes + "0"; 
490          }
491          long l = (long) (factor * fr + 0.5);
492
493          z = leading_zeroes + l;
494          z = z.substring(z.length() - precision, z.length());
495       }
496
497       
498       if (precision > 0 || alternate) z = "." + z;
499       if ((fmt == 'G' || fmt == 'g') && !alternate)
500       // remove trailing zeroes and decimal point
501       {  int t = z.length() - 1;
502          while (t >= 0 && z.charAt(t) == '0') t--;
503          if (t >= 0 && z.charAt(t) == '.') t--;
504          z = z.substring(0, t + 1);
505       }
506       return z;
507    }
508
509    private String exp_format(double d)
510    {  String f = "";
511       int e = 0;
512       double dd = d;
513       double factor = 1;
514       while (dd > 10) { e++; factor /= 10; dd = dd / 10; }
515       while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
516       if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) 
517          return fixed_format(d);
518       
519       d = d * factor;
520       f = f + fixed_format(d);
521       
522       if (fmt == 'e' || fmt == 'g')
523          f = f + "e";
524       else
525          f = f + "E";
526
527       String p = "000";      
528       if (e >= 0) 
529       {  f = f + "+";
530          p = p + e;
531       }
532       else
533       {  f = f + "-";
534          p = p + (-e);
535       }
536          
537       return f + p.substring(p.length() - 3, p.length());
538    }
539    
540    private int width;
541    private int precision;
542    private String pre;
543    private String post;
544    private boolean leading_zeroes;
545    private boolean show_plus;
546    private boolean alternate;
547    private boolean show_space;
548    private boolean left_align;
549    private char fmt; // one of cdeEfgGiosxXos
550 }