001    /*
002      Copyright (C) 2002 Renaud Pawlak <renaud@aopsys.com>
003    
004      This program is free software; you can redistribute it and/or modify
005      it under the terms of the GNU Lesser General Public License as
006      published by the Free Software Foundation; either version 2 of the
007      License, or (at your option) any later version.
008    
009      This program is distributed in the hope that it will be useful,
010      but WITHOUT ANY WARRANTY; without even the implied warranty of
011      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012      GNU Lesser General Public License for more details.
013    
014      You should have received a copy of the GNU Lesser General Public License
015      along with this program; if not, write to the Free Software
016      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
017    
018    package org.objectweb.jac.util;
019    
020    import java.util.Arrays;
021    import java.util.List;
022    
023    public class Enum {
024        String[] values;
025        int start = 0;
026        int step = 1;
027        public Enum(String[] values, int start, int step) {
028            this.values = values;
029            this.start = start;
030            this.step = step;
031        }
032    
033        /**
034         * Converts an integer value to it's string representation
035         * @param index the integer value to convert
036         * @throws InvalidIndexException
037         */
038        public String int2string(int index) {
039            if (((float)(index-start)/((float)step))!=(float)((index-start)/step))
040                throw new InvalidIndexException(index);
041            String value;
042            try {
043                value=values[(index-start)/step];
044            } catch(Exception e) {
045                throw new InvalidIndexException(index);
046            }
047            return value;
048        }
049        /**
050         * Converts a string value to an integer. Throws an exception if
051         * the enum does not define that string.
052         */
053        public int string2int(String string) {
054            if (string==null) 
055                throw new RuntimeException("Invalid string value null for enum");
056            int index = start;
057            for(int i=0; i<values.length; i++) {
058                if (string.equals(values[i])) {
059                    return index;
060                } else {
061                    index += step;
062                }
063            }
064            throw new RuntimeException("Invalid string value '"+string+"' for enum");
065        }
066        public List getValues() {
067            return Arrays.asList(values);
068        }
069        public int getStart() {
070            return start;
071        }
072        public int getStep() {
073            return step;
074        }
075    }