BooleanItemImpl.java

/*
 * SPDX-FileCopyrightText: none
 * SPDX-License-Identifier: CC0-1.0
 */

package gov.nist.secauto.metaschema.core.metapath.item.atomic;

import gov.nist.secauto.metaschema.core.datatype.IDataTypeAdapter;
import gov.nist.secauto.metaschema.core.datatype.adapter.MetaschemaDataTypeProvider;
import gov.nist.secauto.metaschema.core.metapath.item.function.IMapKey;

import edu.umd.cs.findbugs.annotations.NonNull;

class BooleanItemImpl implements IBooleanItem {
  @NonNull
  private static final String TRUE_STRING = "true";
  @NonNull
  private static final String FALSE_STRING = "false";
  @NonNull
  private static final IStringItem TRUE_STRING_ITEM = IStringItem.valueOf(TRUE_STRING);
  @NonNull
  private static final IStringItem FALSE_STRING_ITEM = IStringItem.valueOf(FALSE_STRING);

  private final boolean booleanValue;

  BooleanItemImpl(boolean booleanValue) {
    this.booleanValue = booleanValue;
  }

  @Override
  public Boolean getValue() {
    return toBoolean();
  }

  @Override
  public boolean toBoolean() {
    return booleanValue;
  }

  @Override
  public String asString() {
    return toBoolean() ? TRUE_STRING : FALSE_STRING;
  }

  @Override
  public IStringItem asStringItem() {
    return toBoolean() ? TRUE_STRING_ITEM : FALSE_STRING_ITEM;
  }

  @Override
  public IDataTypeAdapter<?> getJavaTypeAdapter() {
    return MetaschemaDataTypeProvider.BOOLEAN;
  }

  @Override
  public String toString() {
    return asString();
  }

  @Override
  public IMapKey asMapKey() {
    return new MapKey();
  }

  @Override
  public int hashCode() {
    return Boolean.hashCode(booleanValue);
  }

  @SuppressWarnings("PMD.OnlyOneReturn")
  @Override
  public boolean equals(Object obj) {
    return this == obj
        || (obj instanceof IBooleanItem && compareTo((IBooleanItem) obj) == 0);
  }

  private final class MapKey implements IMapKey {
    @Override
    public IBooleanItem getKey() {
      return BooleanItemImpl.this;
    }

    @Override
    public int hashCode() {
      return getKey().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
      return this == obj ||
          (obj instanceof MapKey
              && getKey().equals(((MapKey) obj).getKey()));
    }
  }
}