This is an automated email from the ASF dual-hosted git repository.

alsay pushed a commit to branch tdigest
in repository https://gitbox.apache.org/repos/asf/datasketches-java.git

commit 0623e5215eb81f95941faa8fd6055cd88a8c2830
Author: AlexanderSaydakov <[email protected]>
AuthorDate: Wed Mar 13 14:27:42 2024 -0700

    added getSerializedSizeBytes()
---
 .../apache/datasketches/tdigest/TDigestDouble.java  | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java 
b/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java
index 2dd62c52..9a93b1c1 100644
--- a/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java
+++ b/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java
@@ -288,18 +288,25 @@ public final class TDigestDouble {
     return weightedAverage(centroidWeights_[numCentroids_ - 1], w1, maxValue_, 
w2);
   }
 
+  /**
+   * Computes size needed to serialize the current state.
+   * @return size in bytes needed to serialize this tdigest
+   */
+  int getSerializedSizeBytes() {
+    mergeBuffered(); // side effect
+    return getPreambleLongs() * Long.BYTES
+    + (isEmpty() ? 0 : (isSingleValue() ? Double.BYTES : 2 * Double.BYTES + 
(Double.BYTES + Long.BYTES) * numCentroids_));
+  }
+
   /**
    * Serialize this TDigest to a byte array form.
    * @return byte array
    */
   public byte[] toByteArray() {
     mergeBuffered(); // side effect
-    final byte preambleLongs = isEmpty() || isSingleValue() ? 
PREAMBLE_LONGS_EMPTY_OR_SINGLE : PREAMBLE_LONGS_MULTIPLE;
-    final int sizeBytes = preambleLongs * Long.BYTES
-        + (isEmpty() ? 0 : (isSingleValue() ? Double.BYTES : 2 * Double.BYTES 
+ (Double.BYTES + Long.BYTES) * numCentroids_));
-    final byte[] bytes = new byte[sizeBytes];
+    final byte[] bytes = new byte[getSerializedSizeBytes()];
     final WritableBuffer wbuf = 
WritableMemory.writableWrap(bytes).asWritableBuffer();
-    wbuf.putByte(preambleLongs);
+    wbuf.putByte((byte) getPreambleLongs());
     wbuf.putByte(SERIAL_VERSION);
     wbuf.putByte((byte) Family.TDIGEST.getID());
     wbuf.putShort(k_);
@@ -575,6 +582,10 @@ public final class TDigestDouble {
     return getTotalWeight() == 1;
   }
 
+  private int getPreambleLongs() {
+    return isEmpty() || isSingleValue() ? PREAMBLE_LONGS_EMPTY_OR_SINGLE : 
PREAMBLE_LONGS_MULTIPLE;
+  }
+
   /*
    * Generates cluster sizes proportional to q*(1-q).
    * The use of a normalizing function results in a strictly bounded number of 
clusters no matter how many samples.


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to