1 /* 2 * Copyright 2013 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #include "SkData.h" 9 #include "SkStream.h" 10 #include "SkStreamHelpers.h" 11 #include "SkTypes.h" 12 13 size_t CopyStreamToStorage(SkAutoMalloc* storage, SkStream* stream) { 14 SkASSERT(storage != NULL); 15 SkASSERT(stream != NULL); 16 17 if (stream->hasLength()) { 18 const size_t length = stream->getLength(); 19 void* dst = storage->reset(length); 20 if (stream->read(dst, length) != length) { 21 return 0; 22 } 23 return length; 24 } 25 26 SkDynamicMemoryWStream tempStream; 27 // Arbitrary buffer size. 28 const size_t bufferSize = 256 * 1024; // 256KB 29 char buffer[bufferSize]; 30 SkDEBUGCODE(size_t debugLength = 0;) 31 do { 32 size_t bytesRead = stream->read(buffer, bufferSize); 33 tempStream.write(buffer, bytesRead); 34 SkDEBUGCODE(debugLength += bytesRead); 35 SkASSERT(tempStream.bytesWritten() == debugLength); 36 } while (!stream->isAtEnd()); 37 const size_t length = tempStream.bytesWritten(); 38 void* dst = storage->reset(length); 39 tempStream.copyTo(dst); 40 return length; 41 } 42 43 SkData *CopyStreamToData(SkStream* stream) { 44 SkASSERT(stream != NULL); 45 46 if (stream->hasLength()) { 47 const size_t length = stream->getLength(); 48 void* dst = sk_malloc_throw(length); 49 if (stream->read(dst, length) != length) { 50 return 0; 51 } 52 return SkData::NewFromMalloc(dst, length); 53 } 54 55 SkDynamicMemoryWStream tempStream; 56 // Arbitrary buffer size. 57 const size_t bufferSize = 256 * 1024; // 256KB 58 char buffer[bufferSize]; 59 SkDEBUGCODE(size_t debugLength = 0;) 60 do { 61 size_t bytesRead = stream->read(buffer, bufferSize); 62 tempStream.write(buffer, bytesRead); 63 SkDEBUGCODE(debugLength += bytesRead); 64 SkASSERT(tempStream.bytesWritten() == debugLength); 65 } while (!stream->isAtEnd()); 66 return tempStream.copyToData(); 67 } 68