Skip to content
This repository was archived by the owner on May 8, 2026. It is now read-only.

Commit 54b6848

Browse files
Add getDataSize() to DocumentSnapshot
This method calculates and returns the total size of the data stored in the DocumentSnapshot in bytes. - Iterates through the protobuf `Value` messages in the `fields` map. - Sums the `getSerializedSize()` of each `Value`. - Returns 0 if the document does not exist (fields is null).
1 parent 7920b5b commit 54b6848

2 files changed

Lines changed: 36 additions & 0 deletions

File tree

google-cloud-firestore/src/main/java/com/google/cloud/firestore/DocumentSnapshot.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,4 +468,21 @@ public String toString() {
468468
"%s{doc=%s, fields=%s, readTime=%s, updateTime=%s, createTime=%s}",
469469
getClass().getSimpleName(), docRef, fields, readTime, updateTime, createTime);
470470
}
471+
472+
/**
473+
* Returns the size of the data in this snapshot in bytes.
474+
*
475+
* @return The size of the data in bytes.
476+
*/
477+
public int getDataSize() {
478+
if (fields == null) {
479+
return 0;
480+
}
481+
482+
int totalSize = 0;
483+
for (Value value : fields.values()) {
484+
totalSize += value.getSerializedSize();
485+
}
486+
return totalSize;
487+
}
471488
}

google-cloud-firestore/src/test/java/com/google/cloud/firestore/QueryTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,4 +1521,23 @@ public void inequalityFiltersImplicitlyOrderedLexicographicallyWithExplicitOrder
15211521

15221522
assertEquals(orderFields, query_.createImplicitOrderBy());
15231523
}
1524+
1525+
@Test
1526+
public void documentSnapshotGetDataSize() {
1527+
// Test with an existing document
1528+
DocumentSnapshot snapshot = SINGLE_FIELD_SNAPSHOT;
1529+
int expectedSize = 0;
1530+
for (Value value : snapshot.getProtoFields().values()) {
1531+
expectedSize += value.getSerializedSize();
1532+
}
1533+
assertEquals(expectedSize, snapshot.getDataSize());
1534+
1535+
// Test with a non-existent document
1536+
DocumentSnapshot missingSnapshot =
1537+
DocumentSnapshot.fromMissing(
1538+
firestoreMock,
1539+
firestoreMock.document("coll/doc"),
1540+
Timestamp.now());
1541+
assertEquals(0, missingSnapshot.getDataSize());
1542+
}
15241543
}

0 commit comments

Comments
 (0)