Created
January 11, 2015 13:28
-
-
Save ikeisuke/b5397ce951f88ed78251 to your computer and use it in GitHub Desktop.
swiftでS3のマルチパートアップロード時のETagを計算する ref: http://qiita.com/ikeisuke/items/8222899dd0742112680d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extension NSData { | |
| func s3etag(minimumPartSize: UInt64 = 5 * 1024 * 1024) -> String { | |
| func md5digest(data: NSData) -> NSData { | |
| let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
| let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength) | |
| CC_MD5(data.bytes, CC_LONG(data.length), md5Buffer) | |
| return NSMutableData(bytesNoCopy: md5Buffer, length: digestLength) | |
| } | |
| func md5hexdigext(data: NSData) -> String { | |
| let digestLength = Int(CC_MD5_DIGEST_LENGTH) | |
| let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength) | |
| CC_MD5(data.bytes, CC_LONG(data.length), md5Buffer) | |
| var output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2)) | |
| for i in 0..<digestLength { | |
| output.appendFormat("%02x", md5Buffer[i]) | |
| } | |
| return String(format: output) | |
| } | |
| var size = UInt64(self.length) | |
| if size > minimumPartSize { | |
| var md5s = NSMutableData() | |
| var partCount = UInt64((size + (minimumPartSize / 2)) / minimumPartSize) | |
| for var i:UInt64=0; i<partCount; i++ { | |
| var dataStart = Int(i * minimumPartSize); | |
| var dataLength = Int((i == (partCount - 1)) ? (size - (i * minimumPartSize)) : minimumPartSize) | |
| md5s.appendData(md5digest(self.subdataWithRange(NSMakeRange(dataStart, dataLength)))) | |
| } | |
| return md5hexdigext(md5s) + "-" + String(partCount); | |
| } else { | |
| return md5hexdigext(self) | |
| } | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <CommonCrypto/CommonCrypto.h> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment