Repository: vapor/vapor
File: Sources/Vapor/Utilities/FileIO.swift (Swift)

Code before:
        let fileETag = "\(modifiedAt.timeIntervalSince1970)-\(fileSize)"
        headers.replaceOrAdd(name: .eTag, value: fileETag)

        // Check if file has been cached already and return NotModified response if the etags match
        if fileETag == request.headers.first(name: .ifNoneMatch) {
            return Response(status: .notModified)
        }

        // Create the HTTP response.
        let response = Response(status: .ok, headers: headers)
        var offset: Int64 = 0
        var byteCount: Int = fileSize
        if let contentRange = contentRange {
            response.status = .partialContent
            response.headers.add(name: .accept, value: contentRange.unit.serialize())
            let range = contentRange.ranges[0].asResponseContentRange(limit: fileSize)
            response.headers.contentRange = ContentRangeHeader(unit: contentRange.unit, range: range)
            (offset, byteCount) = contentRange.ranges[0].asByteBufferBounds(withMaxSize: fileSize)
        }
        // Set Content-Type header based on the media type
        // Only set Content-Type if file not modified and returned above.
        if
            let fileExtension = path.components(separatedBy: ".").last,
            let type = HTTPMediaType.fileExtension(fileExtension)
        {
            response.headers.contentType = type
        }

        response.body = .init(stream: { stream in
            self.read(path: path, fromOffset: offset, byteCount: byteCount, chunkSize: chunkSize) { chunk in
                return stream.write(.buffer(chunk))
            }.whenComplete { result in
                switch result {
                case .failure(let error):
                    stream.write(.error(error), promise: nil)
                case .success:
                    stream.write(.end, promise: nil)
                }
            }
        }, count: byteCount)
        
        return response
    }

    /// Private read method. `onRead` closure uses ByteBuffer and expects future return.
    /// There may be use in publicizing this in the future for reads that must be async.
    private func read(
        path: String,
        fromOffset offset: Int64,
        byteCount: Int,
        chunkSize: Int,

Review comment (bug):
Is it safe to assume `!contentRange.ranges.isEmpty`? If it would be `[]` then this code will cause a crash for sure.

Code after:
        else {
            return Response(status: .internalServerError)
        }

        let contentRange: HTTPHeaders.Range?
        if let rangeFromHeaders = request.headers.range {
            if rangeFromHeaders.unit == .bytes && rangeFromHeaders.ranges.count == 1 {
                contentRange = rangeFromHeaders
            } else {
                contentRange = nil
            }
        } else {
            contentRange = nil
        }
        // Create empty headers array.
        var headers: HTTPHeaders = [:]

        // Generate ETag value, "HEX value of last modified date" + "-" + "file size"
        let fileETag = "\(modifiedAt.timeIntervalSince1970)-\(fileSize)"
        headers.replaceOrAdd(name: .eTag, value: fileETag)

        // Check if file has been cached already and return NotModified response if the etags match
        if fileETag == request.headers.first(name: .ifNoneMatch) {
            return Response(status: .notModified)
        }

        // Create the HTTP response.
        let response = Response(status: .ok, headers: headers)
        let offset: Int64
        let byteCount: Int
        if let contentRange = contentRange {
            response.status = .partialContent
            response.headers.add(name: .accept, value: contentRange.unit.serialize())
            if let firstRange = contentRange.ranges.first {
                let range = firstRange.asResponseContentRange(limit: fileSize)
                response.headers.contentRange = HTTPHeaders.ContentRange(unit: contentRange.unit, range: range)
                (offset, byteCount) = firstRange.asByteBufferBounds(withMaxSize: fileSize)
            } else {
                offset = 0
                byteCount = fileSize
            }
        } else {
            offset = 0
            byteCount = fileSize
        }
        // Set Content-Type header based on the media type
        // Only set Content-Type if file not modified and returned above.
        if
            let fileExtension = path.components(separatedBy: ".").last,
            let type = mediaType ?? HTTPMediaType.fileExtension(fileExtension)
        {