All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.prettypb.runtime.include.ExtendableImpl Maven / Gradle / Ivy

The newest version!
package net.dongliu.prettypb.runtime.include;

import java.util.*;

/**
 * implement extend methods.
 * we can switch to defender method in java8 someday
 *
 * @author Dong Liu
 */
public class ExtendableImpl implements Extendable {

    private final ExtensionRange[] extensionRanges;

    private final Map extensionValues;

    public ExtendableImpl(ExtensionRange... extensionRanges) {
        this.extensionRanges = extensionRanges;
        extensionValues = new HashMap<>();
    }

    @Override
    public List getExtensionRangeList() {
        return Arrays.asList(this.extensionRanges);
    }

    @Override
    public boolean tagInExtensions(int tag) {
        for (ExtensionRange extensionRange : this.extensionRanges) {
            if (tag >= extensionRange.getStartTag() && tag <= extensionRange.getEndTag()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public  boolean hasExtension(ExtensionField tag) {
        return extensionValues.containsKey(tag);
    }

    @Override
    public  T getExtension(ExtensionField tag) {
        if (!tagInExtensions(tag.getNumber())) {
            throw new IllegalArgumentException("invalid tag value:" + tag.getNumber());
        }
        return (T) extensionValues.get(tag);
    }

    @Override
    public Map getAllExtensions() {
        return Collections.unmodifiableMap(extensionValues);
    }

    @Override
    public  void setExtension(ExtensionField tag, T value) {
        if (!tagInExtensions(tag.getNumber())) {
            throw new IllegalArgumentException("invalid tag value:" + tag.getNumber());
        }
        extensionValues.put(tag, value);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy