| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
 | // Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Qt-Security score:significant reason:default
#include "qrandomaccessasyncfile_p_p.h"
#include "qiooperation_p.h"
#include "qiooperation_p_p.h"
#include "qplatformdefs.h"
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/private/qfilesystemengine_p.h>
QT_BEGIN_NAMESPACE
namespace {
static bool isBarrierOperation(QIOOperation::Type type)
{
    return type == QIOOperation::Type::Flush || type == QIOOperation::Type::Open;
}
} // anonymous namespace
// Fine to provide the definition here, because all the usages are in this file
// only!
template <typename Operation, typename ...Args>
Operation *
QRandomAccessAsyncFilePrivate::addOperation(QIOOperation::Type type, qint64 offset, Args &&...args)
{
    auto dataStorage = new QtPrivate::QIOOperationDataStorage(std::forward<Args>(args)...);
    auto *priv = new QIOOperationPrivate(dataStorage);
    priv->offset = offset;
    priv->type = type;
    Operation *op = new Operation(*priv, q_ptr);
    auto opId = getNextId();
    m_operations.push_back(OperationInfo(opId, op));
    startOperationsUntilBarrier();
    return op;
}
QRandomAccessAsyncFilePrivate::QRandomAccessAsyncFilePrivate()
    : QObjectPrivate()
{
}
QRandomAccessAsyncFilePrivate::~QRandomAccessAsyncFilePrivate()
        = default;
void QRandomAccessAsyncFilePrivate::init()
{
}
void QRandomAccessAsyncFilePrivate::cancelAndWait(QIOOperation *op)
{
    auto it = std::find_if(m_operations.cbegin(), m_operations.cend(),
                           [op](const auto &opInfo) {
                               return opInfo.operation.get() == op;
                           });
    // not found
    if (it == m_operations.cend())
        return;
    const auto opInfo = m_operations.takeAt(std::distance(m_operations.cbegin(), it));
    if (opInfo.state == OpState::Running) {
        // cancel this operation
        m_mutex.lock();
        if (m_runningOps.contains(opInfo.opId)) {
            m_opToCancel = opInfo.opId;
            closeIoChannel(opInfo.channel);
            m_cancellationCondition.wait(&m_mutex);
            m_opToCancel = kInvalidOperationId; // reset
        }
        m_mutex.unlock();
    } // otherwise it was not started yet
    // clean up the operation
    releaseIoChannel(opInfo.channel);
    auto *priv = QIOOperationPrivate::get(opInfo.operation);
    priv->setError(QIOOperation::Error::Aborted);
    // we could cancel a barrier operation, so try to execute next operations
    startOperationsUntilBarrier();
}
void QRandomAccessAsyncFilePrivate::close()
{
    if (m_fileState == FileState::Closed)
        return;
    // cancel all operations
    m_mutex.lock();
    m_opToCancel = kAllOperationIds;
    for (const auto &op : m_operations)
        closeIoChannel(op.channel);
    closeIoChannel(m_ioChannel);
    // we're not interested in any results anymore
    if (!m_runningOps.isEmpty() || m_ioChannel)
        m_cancellationCondition.wait(&m_mutex);
    m_opToCancel = kInvalidOperationId; // reset
    m_mutex.unlock();
    // clean up all operations
    for (auto &opInfo : m_operations) {
        releaseIoChannel(opInfo.channel);
        auto *priv = QIOOperationPrivate::get(opInfo.operation);
        priv->setError(QIOOperation::Error::Aborted);
    }
    m_operations.clear();
    releaseIoChannel(m_ioChannel);
    if (m_fd >= 0) {
        ::close(m_fd);
        m_fd = -1;
    }
    m_fileState = FileState::Closed;
}
qint64 QRandomAccessAsyncFilePrivate::size() const
{
    if (m_fileState != FileState::Opened)
        return -1;
    QFileSystemMetaData metaData;
    if (QFileSystemEngine::fillMetaData(m_fd, metaData))
        return metaData.size();
    return -1;
}
QIOOperation *
QRandomAccessAsyncFilePrivate::open(const QString &path, QIODeviceBase::OpenMode mode)
{
    if (m_fileState == FileState::Closed) {
        m_filePath = path;
        m_openMode = mode;
        // Open is a barrier, so we won't have two open() operations running
        // in parallel
        m_fileState = FileState::OpenPending;
    }
    return addOperation<QIOOperation>(QIOOperation::Type::Open, 0);
}
QIOOperation *QRandomAccessAsyncFilePrivate::flush()
{
    return addOperation<QIOOperation>(QIOOperation::Type::Flush, 0);
}
QIOReadOperation *QRandomAccessAsyncFilePrivate::read(qint64 offset, qint64 maxSize)
{
    QByteArray array(maxSize, Qt::Uninitialized);
    return addOperation<QIOReadOperation>(QIOOperation::Type::Read, offset, std::move(array));
}
QIOWriteOperation *QRandomAccessAsyncFilePrivate::write(qint64 offset, const QByteArray &data)
{
    QByteArray copy = data;
    return write(offset, std::move(copy));
}
QIOWriteOperation *QRandomAccessAsyncFilePrivate::write(qint64 offset, QByteArray &&data)
{
    return addOperation<QIOWriteOperation>(QIOOperation::Type::Write, offset, std::move(data));
}
QIOVectoredReadOperation *
QRandomAccessAsyncFilePrivate::readInto(qint64 offset, QSpan<std::byte> buffer)
{
    return addOperation<QIOVectoredReadOperation>(QIOOperation::Type::Read, offset,
                                                  QSpan<const QSpan<std::byte>>{buffer});
}
QIOVectoredWriteOperation *
QRandomAccessAsyncFilePrivate::writeFrom(qint64 offset, QSpan<const std::byte> buffer)
{
    return addOperation<QIOVectoredWriteOperation>(QIOOperation::Type::Write, offset,
                                                   QSpan<const QSpan<const std::byte>>{buffer});
}
QIOVectoredReadOperation *
QRandomAccessAsyncFilePrivate::readInto(qint64 offset, QSpan<const QSpan<std::byte>> buffers)
{
    // GCD implementation does not have vectored read. Spawning several read
    // operations (each with an updated offset), is not ideal, because some
    // of them could fail, and it wouldn't be clear what would be the return
    // value in such case.
    // So, we'll just execute several reads one-after-another, and complete the
    // whole operation only when they all finish (or when an operation fails
    // at some point).
    return addOperation<QIOVectoredReadOperation>(QIOOperation::Type::Read, offset, buffers);
}
QIOVectoredWriteOperation *
QRandomAccessAsyncFilePrivate::writeFrom(qint64 offset, QSpan<const QSpan<const std::byte>> buffers)
{
    return addOperation<QIOVectoredWriteOperation>(QIOOperation::Type::Write, offset, buffers);
}
dispatch_io_t QRandomAccessAsyncFilePrivate::createMainChannel(int fd)
{
    auto sharedThis = this;
    return dispatch_io_create(DISPATCH_IO_RANDOM, fd,
                               dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0),
                               ^(int /*error*/) {
                                   // Notify that the file descriptor can be closed
                                   QMutexLocker locker(&sharedThis->m_mutex);
                                   sharedThis->m_cancellationCondition.wakeOne();
                               });
}
dispatch_io_t QRandomAccessAsyncFilePrivate::duplicateIoChannel(OperationId opId)
{
    if (!m_ioChannel)
        return nullptr;
    // We need to create a new channel for each operation, because the only way
    // to cancel an operation is to call dispatch_io_close() with
    // DISPATCH_IO_STOP flag.
    // We do not care about the callback in this case, because we have the
    // callback from the "main" io channel to do all the proper cleanup
    auto channel =
            dispatch_io_create_with_io(DISPATCH_IO_RANDOM, m_ioChannel,
                                       dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0),
                                       ^(int){ /* empty callback */ });
    if (channel) {
        QMutexLocker locker(&m_mutex);
        m_runningOps.insert(opId);
    }
    return channel;
}
void QRandomAccessAsyncFilePrivate::closeIoChannel(dispatch_io_t channel)
{
    if (channel)
        dispatch_io_close(channel, DISPATCH_IO_STOP);
}
void QRandomAccessAsyncFilePrivate::releaseIoChannel(dispatch_io_t channel)
{
    if (channel) {
        dispatch_release(channel);
        channel = nullptr;
    }
}
void QRandomAccessAsyncFilePrivate::handleOperationComplete(const OperationResult &opResult)
{
    // try to start next operations on return
    auto onReturn = qScopeGuard([this] {
        startOperationsUntilBarrier();
    });
    auto it = std::find_if(m_operations.cbegin(), m_operations.cend(),
                           [opId = opResult.opId](const auto &opInfo) {
                               return opInfo.opId == opId;
                           });
    if (it == m_operations.cend())
        return;
    qsizetype idx = std::distance(m_operations.cbegin(), it);
    const OperationInfo info = m_operations.takeAt(idx);
    closeIoChannel(info.channel);
    releaseIoChannel(info.channel);
    if (!info.operation)
        return;
    auto convertError = [](int error, QIOOperation::Type type) {
        if (error == 0) {
            return QIOOperation::Error::None;
        } else if (error == ECANCELED) {
            return QIOOperation::Error::Aborted;
        } else if (error == EBADF) {
            return QIOOperation::Error::FileNotOpen;
        } else if (error == EINVAL) {
            switch (type) {
            case QIOOperation::Type::Read:
            case QIOOperation::Type::Write:
                return QIOOperation::Error::IncorrectOffset;
            case QIOOperation::Type::Flush:
                return QIOOperation::Error::Flush;
            case QIOOperation::Type::Open:
                return QIOOperation::Error::Open;
            case QIOOperation::Type::Unknown:
                Q_UNREACHABLE_RETURN(QIOOperation::Error::FileNotOpen);
            }
        } else {
            switch (type) {
            case QIOOperation::Type::Read:
                return QIOOperation::Error::Read;
            case QIOOperation::Type::Write:
                return QIOOperation::Error::Write;
            case QIOOperation::Type::Flush:
                return QIOOperation::Error::Flush;
            case QIOOperation::Type::Open:
                return QIOOperation::Error::Open;
            case QIOOperation::Type::Unknown:
                Q_UNREACHABLE_RETURN(QIOOperation::Error::FileNotOpen);
            }
        }
    };
    auto *priv = QIOOperationPrivate::get(info.operation);
    switch (priv->type) {
    case QIOOperation::Type::Read:
    case QIOOperation::Type::Write:
        priv->appendBytesProcessed(opResult.result);
        // make sure that read buffers are truncated to the actual amount of
        // bytes read
        if (priv->type == QIOOperation::Type::Read) {
            auto dataStorage = priv->dataStorage.get();
            auto processed = priv->processed;
            if (dataStorage->containsByteArray()) {
                QByteArray &array = dataStorage->getByteArray();
                array.truncate(processed);
            } else if (dataStorage->containsReadSpans()) {
                qint64 left = processed;
                auto &readBuffers = dataStorage->getReadSpans();
                for (auto &s : readBuffers) {
                    const qint64 spanSize = qint64(s.size_bytes());
                    const qint64 newSize = (std::min)(left, spanSize);
                    if (newSize < spanSize)
                        s.chop(spanSize - newSize);
                    left -= newSize;
                }
            }
        }
        priv->operationComplete(convertError(opResult.error, priv->type));
        break;
    case QIOOperation::Type::Flush: {
        const QIOOperation::Error error = convertError(opResult.error, priv->type);
        priv->operationComplete(error);
        break;
    }
    case QIOOperation::Type::Open: {
        const QIOOperation::Error error = convertError(opResult.error, priv->type);
        if (opResult.result >= 0 && error == QIOOperation::Error::None) {
            m_fd = (int)opResult.result;
            m_ioChannel = createMainChannel(m_fd);
            m_fileState = FileState::Opened;
        } else {
            m_fileState = FileState::Closed;
        }
        priv->operationComplete(error);
        break;
    }
    case QIOOperation::Type::Unknown:
        Q_UNREACHABLE();
        break;
    }
}
void QRandomAccessAsyncFilePrivate::queueCompletion(OperationId opId, int error)
{
    const OperationResult res = { opId, 0LL, error };
    QMetaObject::invokeMethod(q_ptr, [this, res] {
        handleOperationComplete(res);
    }, Qt::QueuedConnection);
}
void QRandomAccessAsyncFilePrivate::startOperationsUntilBarrier()
{
    // starts all operations until barrier, or a barrier operation if it's the
    // first one
    bool first = true;
    for (auto &opInfo : m_operations) {
        const bool isBarrier = isBarrierOperation(opInfo.operation->type());
        const bool shouldExecute = (opInfo.state == OpState::Pending) && (!isBarrier || first);
        first = false;
        if (shouldExecute) {
            opInfo.state = OpState::Running;
            switch (opInfo.operation->type()) {
            case QIOOperation::Type::Read:
                executeRead(opInfo);
                break;
            case QIOOperation::Type::Write:
                executeWrite(opInfo);
                break;
            case QIOOperation::Type::Flush:
                executeFlush(opInfo);
                break;
            case QIOOperation::Type::Open:
                executeOpen(opInfo);
                break;
            case QIOOperation::Type::Unknown:
                Q_UNREACHABLE();
                break;
            }
        }
        if (isBarrier)
            break;
    }
}
void QRandomAccessAsyncFilePrivate::executeRead(OperationInfo &opInfo)
{
    opInfo.channel = duplicateIoChannel(opInfo.opId);
    if (!opInfo.channel) {
        queueCompletion(opInfo.opId, EBADF);
        return;
    }
    auto priv = QIOOperationPrivate::get(opInfo.operation);
    auto dataStorage = priv->dataStorage.get();
    if (dataStorage->containsByteArray()) {
        auto &array = dataStorage->getByteArray();
        char *bytesPtr = array.data();
        qint64 maxSize = array.size();
        readOneBufferHelper(opInfo.opId, opInfo.channel, priv->offset,
                            bytesPtr, maxSize,
                            0, 1, 0);
    } else {
        Q_ASSERT(dataStorage->containsReadSpans());
        auto &readBuffers = dataStorage->getReadSpans();
        const auto totalBuffers = readBuffers.size();
        if (totalBuffers == 0) {
            queueCompletion(opInfo.opId, 0);
            return;
        }
        auto buf = readBuffers[0];
        readOneBufferHelper(opInfo.opId, opInfo.channel, priv->offset,
                            buf.data(), buf.size(),
                            0, totalBuffers, 0);
    }
}
void QRandomAccessAsyncFilePrivate::executeWrite(OperationInfo &opInfo)
{
    opInfo.channel = duplicateIoChannel(opInfo.opId);
    if (!opInfo.channel) {
        queueCompletion(opInfo.opId, EBADF);
        return;
    }
    auto priv = QIOOperationPrivate::get(opInfo.operation);
    auto dataStorage = priv->dataStorage.get();
    if (dataStorage->containsByteArray()) {
        const auto &array = dataStorage->getByteArray();
        const char *dataPtr = array.constData();
        const qint64 dataSize = array.size();
        dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0);
        // We handle the bytes on our own, so we need to specify an empty block as
        // a destructor.
        // dataToWrite is retained, so should be properly cleaned up. We always do
        // it in the callback.
        dispatch_data_t dataToWrite = dispatch_data_create(dataPtr, dataSize, queue, ^{});
        writeHelper(opInfo.opId, opInfo.channel, priv->offset, dataToWrite, dataSize);
    } else {
        Q_ASSERT(dataStorage->containsWriteSpans());
        const auto &writeBuffers = dataStorage->getWriteSpans();
        const auto totalBuffers = writeBuffers.size();
        if (totalBuffers == 0) {
            queueCompletion(opInfo.opId, 0);
            return;
        }
        dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0);
        qsizetype idx = 0;
        dispatch_data_t dataToWrite = dispatch_data_empty;
        qint64 totalSize = 0;
        do {
            const std::byte *dataPtr = writeBuffers[idx].data();
            const qint64 dataSize = writeBuffers[idx].size();
            dispatch_data_t data = dispatch_data_create(dataPtr, dataSize, queue, ^{});
            dataToWrite = dispatch_data_create_concat(dataToWrite, data);
            [data release];
            totalSize += dataSize;
        } while (++idx < totalBuffers);
        writeHelper(opInfo.opId, opInfo.channel, priv->offset, dataToWrite, totalSize);
    }
}
void QRandomAccessAsyncFilePrivate::executeFlush(OperationInfo &opInfo)
{
    opInfo.channel = duplicateIoChannel(opInfo.opId);
    if (!opInfo.channel) {
        queueCompletion(opInfo.opId, EBADF);
        return;
    }
    // flush() is a barrier operation, but dispatch_io_barrier does not work
    // as documented with multiple channels :(
    auto sharedThis = this;
    const int fd = m_fd;
    const OperationId opId = opInfo.opId;
    dispatch_io_barrier(opInfo.channel, ^{
        const int err = fsync(fd);
        QMutexLocker locker(&sharedThis->m_mutex);
        sharedThis->m_runningOps.remove(opId);
        const auto cancelId = sharedThis->m_opToCancel;
        if (cancelId == kAllOperationIds || cancelId == opId) {
            if (cancelId == opId)
                sharedThis->m_cancellationCondition.wakeOne();
        } else {
            auto context = sharedThis->q_ptr;
            const OperationResult res = { opId, 0LL, err };
            QMetaObject::invokeMethod(context, [sharedThis](const OperationResult &r) {
                sharedThis->handleOperationComplete(r);
            }, Qt::QueuedConnection, res);
        }
    });
}
// stolen from qfsfileengine_unix.cpp
static inline int openModeToOpenFlags(QIODevice::OpenMode mode)
{
    int oflags = QT_OPEN_RDONLY;
#ifdef QT_LARGEFILE_SUPPORT
    oflags |= QT_OPEN_LARGEFILE;
#endif
    if ((mode & QIODevice::ReadWrite) == QIODevice::ReadWrite)
        oflags = QT_OPEN_RDWR;
    else if (mode & QIODevice::WriteOnly)
        oflags = QT_OPEN_WRONLY;
    if ((mode & QIODevice::WriteOnly)
        && !(mode & QIODevice::ExistingOnly)) // QFSFileEnginePrivate::openModeCanCreate(mode))
        oflags |= QT_OPEN_CREAT;
    if (mode & QIODevice::Truncate)
        oflags |= QT_OPEN_TRUNC;
    if (mode & QIODevice::Append)
        oflags |= QT_OPEN_APPEND;
    if (mode & QIODevice::NewOnly)
        oflags |= QT_OPEN_EXCL;
    return oflags;
}
void QRandomAccessAsyncFilePrivate::executeOpen(OperationInfo &opInfo)
{
    if (m_fileState != FileState::OpenPending) {
        queueCompletion(opInfo.opId, EINVAL);
        return;
    }
    const QByteArray nativeName = QFile::encodeName(QDir::toNativeSeparators(m_filePath));
    int openFlags = openModeToOpenFlags(m_openMode);
    openFlags |= O_NONBLOCK;
    auto sharedThis = this;
    const OperationId opId = opInfo.opId;
    // We don'd call duplicateIOChannel(), so need to update the running ops
    // explicitly.
    m_mutex.lock();
    m_runningOps.insert(opId);
    m_mutex.unlock();
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0),
                   ^{
                       int err = 0;
                       const int fd = ::open(nativeName.data(), openFlags);
                       if (fd < 0)
                           err = errno;
                       QMutexLocker locker(&sharedThis->m_mutex);
                       sharedThis->m_runningOps.remove(opId);
                       const auto cancelId = sharedThis->m_opToCancel;
                       if (cancelId == kAllOperationIds || cancelId == opId) {
                           // open() is a barrier operation, so it's always the
                           // only executing operation.
                           // Also, the main IO channel is not created yet.
                           // So we need to notify the condition variable in
                           // any both cases.
                           Q_ASSERT(sharedThis->m_runningOps.isEmpty());
                           sharedThis->m_cancellationCondition.wakeOne();
                       } else {
                           auto context = sharedThis->q_ptr;
                           const OperationResult res = { opId, qint64(fd), err };
                           QMetaObject::invokeMethod(context, [sharedThis](const OperationResult &r) {
                               sharedThis->handleOperationComplete(r);
                           }, Qt::QueuedConnection, res);
                       }
                   });
}
void QRandomAccessAsyncFilePrivate::readOneBuffer(OperationId opId, qsizetype bufferIdx,
                                                  qint64 alreadyRead)
{
    // we need to lookup the operation again, because it could have beed removed
    // by the user...
    auto it = std::find_if(m_operations.cbegin(), m_operations.cend(),
                           [opId](const auto &opInfo) {
                               return opId == opInfo.opId;
                           });
    if (it == m_operations.cend())
        return;
    auto op = it->operation; // QPointer could be null
    if (!op) {
        closeIoChannel(it->channel);
        return;
    }
    auto *priv = QIOOperationPrivate::get(op);
    Q_ASSERT(priv->type == QIOOperation::Type::Read);
    Q_ASSERT(priv->dataStorage->containsReadSpans());
    auto &readBuffers = priv->dataStorage->getReadSpans();
    Q_ASSERT(readBuffers.size() > bufferIdx);
    qint64 newOffset = priv->offset;
    for (qsizetype idx = 0; idx < bufferIdx; ++idx)
        newOffset += readBuffers[idx].size();
    std::byte *bytesPtr = readBuffers[bufferIdx].data();
    qint64 maxSize = readBuffers[bufferIdx].size();
    readOneBufferHelper(opId, it->channel, newOffset, bytesPtr, maxSize, bufferIdx,
                        readBuffers.size(), alreadyRead);
}
void QRandomAccessAsyncFilePrivate::readOneBufferHelper(OperationId opId, dispatch_io_t channel,
                                                        qint64 offset, void *bytesPtr,
                                                        qint64 maxSize, qsizetype currentBufferIdx,
                                                        qsizetype totalBuffers, qint64 alreadyRead)
{
    auto sharedThis = this;
    __block size_t readFromBuffer = 0;
    dispatch_io_read(channel, offset, maxSize,
                     dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0),
                     ^(bool done, dispatch_data_t data, int error) {
                         // Handle data. If there's an error, handle as much as
                         // we can.
                         if (data) {
                             dispatch_data_apply(data, ^(dispatch_data_t /*region*/, size_t offset,
                                                         const void *buffer, size_t size) {
                                 const char *startPtr =
                                         reinterpret_cast<const char *>(buffer) + offset;
                                 // NOTE: This is a copy, but looks like we
                                 // cannot do better :(
                                 std::memcpy((std::byte *)bytesPtr + readFromBuffer,
                                             startPtr, size);
                                 readFromBuffer += size;
                                 return true;  // Keep processing if there is more data.
                             });
                         }
                         QMutexLocker locker(&sharedThis->m_mutex);
                         const auto cancelId = sharedThis->m_opToCancel;
                         if (cancelId == kAllOperationIds || cancelId == opId) {
                             sharedThis->m_runningOps.remove(opId);
                             if (cancelId == opId)
                                 sharedThis->m_cancellationCondition.wakeOne();
                         } else if (done) {
                             sharedThis->m_runningOps.remove(opId);
                             auto context = sharedThis->q_ptr;
                             // if error, or last buffer, or read less than expected,
                             // report operation completion
                             qint64 totalRead = qint64(readFromBuffer) + alreadyRead;
                             qsizetype nextBufferIdx = currentBufferIdx + 1;
                             if (error || nextBufferIdx == totalBuffers
                                 || qint64(readFromBuffer) != maxSize) {
                                 const OperationResult res = { opId, totalRead, error };
                                 QMetaObject::invokeMethod(context,
                                     [sharedThis](const OperationResult &r) {
                                         sharedThis->handleOperationComplete(r);
                                     }, Qt::QueuedConnection, res);
                             } else {
                                 // else execute read for the next buffer
                                 QMetaObject::invokeMethod(context,
                                     [sharedThis, opId, nextBufferIdx, totalRead] {
                                         sharedThis->readOneBuffer(opId, nextBufferIdx, totalRead);
                                     }, Qt::QueuedConnection);
                             }
                         }
                     });
}
void QRandomAccessAsyncFilePrivate::writeHelper(OperationId opId, dispatch_io_t channel,
                                                qint64 offset, dispatch_data_t dataToWrite,
                                                qint64 dataSize)
{
    auto sharedThis = this;
    dispatch_io_write(channel, offset, dataToWrite,
                      dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0),
                      ^(bool done, dispatch_data_t data, int error) {
                          // Either an error or complete write.
                          // If there's an error, return the amount that we have
                          // written so far
                          QMutexLocker locker(&sharedThis->m_mutex);
                          const auto cancelId = sharedThis->m_opToCancel;
                          if (cancelId == kAllOperationIds || cancelId == opId) {
                              // Operation is canceled - do nothing
                              sharedThis->m_runningOps.remove(opId);
                              if (cancelId == opId)
                                  sharedThis->m_cancellationCondition.wakeOne();
                          } else if (done) {
                              sharedThis->m_runningOps.remove(opId);
                              // if no error, an attempt to access the data will
                              // crash, because it seems to have no buffer
                              // allocated (as everything was written)
                              const size_t toBeWritten =
                                      (error == 0) ? 0 : dispatch_data_get_size(data);
                              const size_t written = dataSize - toBeWritten;
                              [dataToWrite release];
                              auto context = sharedThis->q_ptr;
                              const OperationResult res = { opId, qint64(written), error };
                              QMetaObject::invokeMethod(context,
                                  [sharedThis](const OperationResult &r) {
                                      sharedThis->handleOperationComplete(r);
                                  }, Qt::QueuedConnection, res);
                          }
                      });
}
QRandomAccessAsyncFilePrivate::OperationId QRandomAccessAsyncFilePrivate::getNextId()
{
    // never return reserved values
    static OperationId opId = kInvalidOperationId;
    if (++opId == kAllOperationIds)
        opId = kInvalidOperationId + 1;
    return opId;
}
QT_END_NAMESPACE
 |