/*
 * Copyright (c) 2018-2019 Atmosphère-NX
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */
#pragma once
#include "../defines.hpp"
namespace ams::util {
    namespace impl {
        template
        union OffsetOfImpl {
            Member Parent::* ptr;
            intptr_t offset;
        };
        template
        constexpr inline Parent *GetParentOfMemberImpl(Member *member, Member Parent::* ptr) {
            return reinterpret_cast(reinterpret_cast(member) - OffsetOfImpl{ ptr }.offset);
        }
        template
        constexpr inline Parent const *GetParentOfMemberImpl(Member const *member, Member Parent::* ptr) {
            return reinterpret_cast(reinterpret_cast(member) - OffsetOfImpl{ ptr }.offset);
        }
        template
        struct GetMemberPointerTraits;
        template
        struct GetMemberPointerTraits {
            using Parent = P;
            using Member = M;
        };
        template
        using GetParentType = typename GetMemberPointerTraits::Parent;
        template
        using GetMemberType = typename GetMemberPointerTraits::Member;
    }
    template
    constexpr inline impl::GetParentType *GetParentPointer(impl::GetMemberType *member) {
        return impl::GetParentOfMemberImpl, impl::GetMemberType>(member, MemberPtr);
    }
    template
    constexpr inline impl::GetParentType const *GetParentPointer(impl::GetMemberType const *member) {
        return impl::GetParentOfMemberImpl, impl::GetMemberType>(member, MemberPtr);
    }
    template
    constexpr inline impl::GetParentType &GetParentReference(impl::GetMemberType *member) {
        return *impl::GetParentOfMemberImpl, impl::GetMemberType>(member, MemberPtr);
    }
    template
    constexpr inline impl::GetParentType const &GetParentReference(impl::GetMemberType const *member) {
        return *impl::GetParentOfMemberImpl, impl::GetMemberType>(member, MemberPtr);
    }
}