001package org.unix4j.unix.find;
002
003import org.unix4j.option.Option;
004import org.unix4j.option.OptionSet;
005
006class OptionableUtil {
007
008        /**
009         * Finds an enum constant by a given option through the enum/option
010         * association given by the {@link Optionable} interface implemented by the
011         * enum. If no enum constant is found for the given option, null is
012         * returned.
013         * 
014         * @param <O>
015         *            the option type
016         * @param <E>
017         *            the enum type
018         * @param enumClass
019         *            the enum class
020         * @param option
021         *            the option to look for
022         * @return the enum constant that is associated with the given option
023         */
024        public static <O extends Option, E extends Enum<E> & Optionable<O>> E findEnumByOption(Class<E> enumClass, O option) {
025                for (E e : enumClass.getEnumConstants()) {
026                        if (option.equals(e.getOption())) {
027                                return e;
028                        }
029                }
030                return null;
031        }
032
033        /**
034         * Finds an enum constant by a comparing the options associated with the
035         * enum constant with the options in the specified set. The enum/option
036         * association is defined by the {@link Optionable} interface implemented by
037         * the enum.
038         * <p>
039         * If no enum constant is found with an associated option in the given set,
040         * the specified {@code defaultEnum} value is returned. If multiple enum
041         * constants have an associated option in the given set, the first enum with
042         * such an option is returned.
043         * 
044         * @param <O>
045         *            the option type
046         * @param <E>
047         *            the enum type
048         * @param enumClass
049         *            the enum class
050         * @param optionSet
051         *            the option set to lookup associated options
052         * @param defaultEnum
053         *            the default enum value returned if no enum has an associated
054         *            option in the given option set
055         * @return the enum constant that is associated with the given option
056         */
057        public static <O extends Option, E extends Enum<E> & Optionable<O>> E findFirstEnumByOptionInSet(Class<E> enumClass, OptionSet<O> optionSet, E defaultEnum) {
058                for (E e : enumClass.getEnumConstants()) {
059                        if (optionSet.isSet(e.getOption())) {
060                                return e;
061                        }
062                }
063                return defaultEnum;
064        }
065
066        // no instances
067        private OptionableUtil() {
068                super();
069        };
070}