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

me.moros.bending.api.util.data.SimpleDataContainer Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2020-2024 Moros
 *
 * This file is part of Bending.
 *
 * Bending is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bending is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bending. If not, see .
 */

package me.moros.bending.api.util.data;

import java.util.Map;
import java.util.Optional;

import org.checkerframework.checker.nullness.qual.Nullable;

class SimpleDataContainer implements DataContainer {
  private final Map, Object> data;

  SimpleDataContainer(Map, Object> data) {
    this.data = data;
  }

  @Override
  public  Optional get(DataKey key) {
    return Optional.ofNullable(cast(key.type(), data.get(key)));
  }

  @Override
  public  void add(DataKey key, T value) {
    data.put(key, value);
  }

  @Override
  public  void remove(DataKey key) {
    data.remove(key);
  }

  @Override
  public  boolean canEdit(DataKey key) {
    return true;
  }

  @Override
  public > T toggle(DataKey key, T defaultValue) {
    T oldValue = cast(key.type(), data.computeIfAbsent(key, k -> defaultValue));
    if (oldValue != null && !canEdit(key)) {
      return oldValue;
    }
    T newValue = toggle(oldValue == null ? defaultValue : oldValue);
    add(key, newValue);
    return newValue;
  }

  @Override
  public boolean isEmpty() {
    return data.isEmpty();
  }

  private > T toggle(T oldValue) {
    T[] values = oldValue.getDeclaringClass().getEnumConstants();
    int index = (oldValue.ordinal() + 1) % values.length;
    return values[index];
  }

  private  @Nullable T cast(Class type, Object value) {
    if (type.isInstance(value)) {
      return type.cast(value);
    }
    return null;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy