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

org.klojang.path.PrimitiveArraySegmentWriter Maven / Gradle / Ivy

Go to download

Klojang Invoke is a Java module focused on path-based object access and dynamic invocation. Its central classes are the Path class and the PathWalker class. The Path class captures a path through an object graph. For example "employee.address.city". The PathWalker class lets you read from and write to a wide variety of types using Path objects.

There is a newer version: 21.1.0
Show newest version
package org.klojang.path;

import java.util.OptionalInt;

import static org.klojang.path.PathWalkerException.indexExpected;
import static org.klojang.path.PathWalkerException.indexOutOfBounds;
import static org.klojang.util.InvokeMethods.getArrayLength;
import static org.klojang.util.InvokeMethods.setArrayElement;
import static org.klojang.convert.NumberMethods.toInt;

final class PrimitiveArraySegmentWriter extends
    SegmentWriter {

  PrimitiveArraySegmentWriter(boolean suppressExceptions,
      KeyDeserializer keyDeserializer) {
    super(suppressExceptions, keyDeserializer);
  }

  @Override
  boolean write(Object array, Path path, Object value) {
    int segment = path.size() - 1;
    OptionalInt opt = toInt(path.segment(segment));
    if (opt.isEmpty()) {
      return deadEnd(indexExpected(path, segment));
    }
    int idx = opt.getAsInt();
    int len = getArrayLength(array);
    if (idx >= 0 && idx < len) {
      setArrayElement(array, idx, value);
      return true;
    }
    return deadEnd(indexOutOfBounds(path, segment));
  }

}