#pragma once

#include "chunks.h"

namespace NSrvKernel {
    // Note that this function behaves differently from Split.
    // It does not produce empty chunks.
    static inline std::pair<TChunkList, size_t> DoCutPrefix(size_t prefixLen, TChunkList& from) noexcept {
        const size_t initialLen = prefixLen;
        TChunkList prefix;

        while (prefixLen && !from.Empty()) {
            NSrvKernel::TChunkPtr cur = from.PopFront();
            const auto curLength = cur->Length();

            if (!curLength) {
                continue;
            }

            if (curLength <= prefixLen) {
                prefixLen -= curLength;
                prefix.Push(std::move(cur));
            } else {
                prefix.Push(cur->SubChunk(prefixLen));
                cur->Skip(prefixLen);
                from.Prepend(std::move(cur));
                prefixLen = 0;
            }
        }

        return {std::move(prefix), initialLen - prefixLen};
    }

    static inline TChunkList CutPrefix(size_t prefixLen, TChunkList& from) noexcept {
        return DoCutPrefix(prefixLen, from).first;
    }
}
