Skip to content

Commit cded234

Browse files
committed
Fix writes with 0 length
1 parent d3224b3 commit cded234

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

gcloud-java-storage/src/main/java/com/google/gcloud/spi/DefaultStorageRpc.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,12 +461,20 @@ public Tuple<String, byte[]> read(StorageObject from, Map<Option, ?> options, lo
461461
public void write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length,
462462
boolean last) {
463463
try {
464+
if (length == 0 && !last) {
465+
return;
466+
}
464467
GenericUrl url = new GenericUrl(uploadId);
465468
HttpRequest httpRequest = storage.getRequestFactory().buildPutRequest(url,
466469
new ByteArrayContent(null, toWrite, toWriteOffset, length));
467470
long limit = destOffset + length;
468471
StringBuilder range = new StringBuilder("bytes ");
469-
range.append(destOffset).append('-').append(limit - 1).append('/');
472+
if (length == 0) {
473+
range.append('*');
474+
} else {
475+
range.append(destOffset).append('-').append(limit - 1);
476+
}
477+
range.append('/');
470478
if (last) {
471479
range.append(limit);
472480
} else {

gcloud-java-storage/src/test/java/com/google/gcloud/storage/it/ITStorageTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -823,6 +823,29 @@ public void testReadAndWriteChannels() throws IOException {
823823
assertTrue(storage.delete(BUCKET, blobName));
824824
}
825825

826+
@Test
827+
public void testReadAndWriteChannelsWithDifferentFileSize() throws IOException {
828+
String blobNamePrefix = "test-read-and-write-channels-blob-";
829+
int[] blobSizes = {0, 700, 1024 * 256, 2 * 1024 * 1024, 4 * 1024 * 1024, 4 * 1024 * 1024 + 1};
830+
Random rnd = new Random();
831+
for (int blobSize : blobSizes) {
832+
String blobName = blobNamePrefix + blobSize;
833+
BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build();
834+
byte[] bytes = new byte[blobSize];
835+
rnd.nextBytes(bytes);
836+
try (WriteChannel writer = storage.writer(blob)) {
837+
writer.write(ByteBuffer.wrap(BLOB_BYTE_CONTENT));
838+
}
839+
ByteBuffer readBytes;
840+
try (ReadChannel reader = storage.reader(blob.blobId())) {
841+
readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length);
842+
reader.read(readBytes);
843+
}
844+
assertArrayEquals(BLOB_BYTE_CONTENT, readBytes.array());
845+
assertTrue(storage.delete(BUCKET, blobName));
846+
}
847+
}
848+
826849
@Test
827850
public void testReadAndWriteCaptureChannels() throws IOException {
828851
String blobName = "test-read-and-write-capture-channels-blob";

0 commit comments

Comments
 (0)