/*
 * Copyright (C) 2014, 2015 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "SegregatedFreeList.h"

namespace bmalloc {

SegregatedFreeList::SegregatedFreeList(Owner owner)
    : m_owner(owner)
{
    BASSERT(static_cast<size_t>(&select(largeMax) - m_freeLists.begin()) == m_freeLists.size() - 1);
}

void SegregatedFreeList::insert(const LargeObject& largeObject)
{
    BASSERT(largeObject.owner() == m_owner);
    auto& list = select(largeObject.size());
    list.push(m_owner, largeObject);
}

LargeObject SegregatedFreeList::takeGreedy()
{
    for (size_t i = m_freeLists.size(); i-- > 0; ) {
        LargeObject largeObject = m_freeLists[i].takeGreedy(m_owner);
        if (!largeObject)
            continue;

        return largeObject;
    }
    return LargeObject();
}

LargeObject SegregatedFreeList::take(size_t size)
{
    for (auto* list = &select(size); list != m_freeLists.end(); ++list) {
        LargeObject largeObject = list->take(m_owner, size);
        if (!largeObject)
            continue;

        return largeObject;
    }
    return LargeObject();
}

LargeObject SegregatedFreeList::take(size_t alignment, size_t size, size_t unalignedSize)
{
    for (auto* list = &select(size); list != m_freeLists.end(); ++list) {
        LargeObject largeObject = list->take(m_owner, alignment, size, unalignedSize);
        if (!largeObject)
            continue;

        return largeObject;
    }
    return LargeObject();
}

INLINE auto SegregatedFreeList::select(size_t size) -> FreeList&
{
    size_t alignCount = (size - largeMin) / largeAlignment;
    size_t result = 0;
    while (alignCount) {
        ++result;
        alignCount >>= 1;
    }
    return m_freeLists[result];
}

} // namespace bmalloc
