001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one or more
003 *  contributor license agreements.  See the NOTICE file distributed with
004 *  this work for additional information regarding copyright ownership.
005 *  The ASF licenses this file to You under the Apache License, Version 2.0
006 *  (the "License"); you may not use this file except in compliance with
007 *  the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 *  Unless required by applicable law or agreed to in writing, software
012 *  distributed under the License is distributed on an "AS IS" BASIS,
013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 *  See the License for the specific language governing permissions and
015 *  limitations under the License.
016 */
017package org.apache.commons.compress.harmony.unpack200.bytecode;
018
019import java.io.DataOutputStream;
020import java.io.IOException;
021import java.util.Objects;
022
023/**
024 * UTF8 constant pool entry, used for storing long Strings.
025 */
026public class CPUTF8 extends ConstantPoolEntry {
027
028    private final String utf8;
029
030    /**
031     * Creates a new CPUTF8 instance
032     *
033     * @param utf8 TODO
034     * @param globalIndex - index in CpBands
035     * @throws NullPointerException if utf8 is null
036     */
037    public CPUTF8(final String utf8, final int globalIndex) {
038        super(ConstantPoolEntry.CP_UTF8, globalIndex);
039        this.utf8 = Objects.requireNonNull(utf8, "utf8");
040    }
041
042    public CPUTF8(final String string) {
043        this(string, -1);
044    }
045
046    @Override
047    public boolean equals(final Object obj) {
048        if (this == obj) {
049            return true;
050        }
051        if (obj == null) {
052            return false;
053        }
054        if (this.getClass() != obj.getClass()) {
055            return false;
056        }
057        final CPUTF8 other = (CPUTF8) obj;
058        return utf8.equals(other.utf8);
059    }
060
061    private boolean hashcodeComputed;
062    private int cachedHashCode;
063
064    private void generateHashCode() {
065        hashcodeComputed = true;
066        final int PRIME = 31;
067        cachedHashCode = PRIME + utf8.hashCode();
068    }
069
070    @Override
071    public int hashCode() {
072        if (!hashcodeComputed) {
073            generateHashCode();
074        }
075        return cachedHashCode;
076    }
077
078    @Override
079    public String toString() {
080        return "UTF8: " + utf8;
081    }
082
083    @Override
084    protected void writeBody(final DataOutputStream dos) throws IOException {
085        dos.writeUTF(utf8);
086    }
087
088    public String underlyingString() {
089        return utf8;
090    }
091
092    public void setGlobalIndex(final int index) {
093        globalIndex = index;
094    }
095}