/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.memory;

import com.facebook.common.internal.Preconditions;
import com.facebook.infer.annotation.Nullsafe;

@Nullsafe(Nullsafe.Mode.STRICT)
public class MemoryChunkUtil {

  /**
   * Computes number of bytes that can be safely read/written starting at given offset, but no more
   * than count.
   */
  static int adjustByteCount(final int offset, final int count, final int memorySize) {
    final int available = Math.max(0, memorySize - offset);
    return Math.min(available, count);
  }

  /** Check that copy/read/write operation won't access memory it should not */
  static void checkBounds(
      final int offset,
      final int otherLength,
      final int otherOffset,
      final int count,
      final int memorySize) {
    Preconditions.checkArgument(count >= 0);
    Preconditions.checkArgument(offset >= 0);
    Preconditions.checkArgument(otherOffset >= 0);
    Preconditions.checkArgument(offset + count <= memorySize);
    Preconditions.checkArgument(otherOffset + count <= otherLength);
  }
}

@@ -992,24 +992,52 @@
 t(count %3E= 0
+, %22count (%25d) ! %3E= 0%22, count
 );%0A    Preco
@@ -1062,32 +1062,62 @@
 ment(offset %3E= 0
+, %22offset (%25d) ! %3E= 0%22, offset
 );%0A    Precondit
@@ -1151,16 +1151,56 @@
 set %3E= 0
+, %22otherOffset (%25d) ! %3E= 0%22, otherOffset
 );%0A    P
@@ -1222,24 +1222,33 @@
 eckArgument(
+%0A        
 offset + cou
@@ -1252,16 +1252,111 @@
 count %3C=
+ memorySize,%0A        %22offset (%25d) + count (%25d) ! %3C= %25d%22,%0A        offset,%0A        count,%0A       
  memoryS
@@ -1385,32 +1385,41 @@
 s.checkArgument(
+%0A        
 otherOffset + co
@@ -1424,16 +1424,122 @@
 count %3C=
+ otherLength,%0A        %22otherOffset (%25d) + count (%25d) ! %3C= %25d%22,%0A        otherOffset,%0A        count,%0A       
  otherLe

Add messages to Precondition checks in MemoryChunkUtil