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;
021
022/**
023 * String constant pool entry.
024 */
025public class CPString extends CPConstant {
026
027    private transient int nameIndex;
028    private final CPUTF8 name;
029
030    private boolean hashCodeComputed;
031
032    private int cachedHashCode;
033
034    public CPString(final CPUTF8 value, final int globalIndex) {
035        super(CP_String, value, globalIndex);
036        this.name = value;
037    }
038
039    private void generateHashCode() {
040        hashCodeComputed = true;
041        final int PRIME = 31;
042        int result = 1;
043        result = PRIME * result + name.hashCode();
044        cachedHashCode = result;
045    }
046
047    @Override
048    protected ClassFileEntry[] getNestedClassFileEntries() {
049        return new ClassFileEntry[] { name };
050    }
051
052    @Override
053    public int hashCode() {
054        if (!hashCodeComputed) {
055            generateHashCode();
056        }
057        return cachedHashCode;
058    }
059
060    /**
061     * Allows the constant pool entries to resolve their nested entries
062     *
063     * @param pool TODO
064     */
065    @Override
066    protected void resolve(final ClassConstantPool pool) {
067        super.resolve(pool);
068        nameIndex = pool.indexOf(name);
069    }
070
071    @Override
072    public String toString() {
073        return "String: " + getValue();
074    }
075
076    @Override
077    protected void writeBody(final DataOutputStream dos) throws IOException {
078        dos.writeShort(nameIndex);
079    }
080}