类 ListHashUtil

java.lang.Object
io.agentscope.core.session.ListHashUtil

public final class ListHashUtil extends Object
Utility class for computing hash values of state lists.

This class provides hash computation for change detection in Session implementations. The hash is used to detect if a list has been modified (not just appended) since the last save operation.

The hash computation uses a sampling strategy to avoid iterating over large lists:

  • For small lists (≤5 elements): all elements are included
  • For large lists: samples at positions 0, 1/4, 1/2, 3/4, and last

Usage in Session implementations:


 String currentHash = ListHashUtil.computeHash(values);
 String storedHash = readStoredHash();

 if (storedHash != null && !storedHash.equals(currentHash)) {
     // List was modified, need full rewrite
     rewriteEntireList(values);
 } else if (values.size() > existingCount) {
     // List grew, can append incrementally
     appendNewItems(values);
 }
 
  • 方法详细资料

    • computeHash

      public static String computeHash(List<? extends State> values)
      Compute a hash value for a list of state objects.

      The hash includes:

      • List size
      • Hash codes of sampled elements

      This method is designed to be lightweight and fast, using sampling for large lists to avoid O(n) iteration.

      参数:
      values - the list of state objects to hash
      返回:
      a hex string hash representing the list content
    • hasChanged

      public static boolean hasChanged(String currentHash, String storedHash)
      Check if the list has changed based on hash comparison.
      参数:
      currentHash - the hash of the current list
      storedHash - the previously stored hash (may be null)
      返回:
      true if the list has changed, false otherwise
    • needsFullRewrite

      public static boolean needsFullRewrite(List<? extends State> currentValues, String storedHash, int existingCount)
      Determine if a full rewrite is needed based on list content and existing count.
      参数:
      currentValues - the current complete list of state objects
      storedHash - the previously stored hash (may be null)
      existingCount - the count of items already stored
      返回:
      true if full rewrite is needed, false if incremental append is sufficient