/*
  WDL - aggarray.h
  Copyright (C) 2022 and later, Giorgos Vougioukas

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
*/

#ifndef _WDL_AGGARRAY_H_
#define _WDL_AGGARRAY_H_

#include "wdltypes.h"

#define WDL_ARRAYCOUNT(x) ((int)sizeof(x)/(int)sizeof(x[0]))

template<class PTRTYPE, int SZ> class WDL_PtrArray
{
public:
  explicit WDL_PtrArray(PTRTYPE *val) : m_sb(val)
  {}
  ~WDL_PtrArray()
  {}

  PTRTYPE *Get() const { return m_sb; }
  int GetSize() const { return SZ; }

  int Find(PTRTYPE val) const
  {
    for (int i = 0; i < SZ; i++) if (m_sb[i] == val) return i;
    return -1;
  }

  const PTRTYPE *begin() const { return Get(); }
  const PTRTYPE *end() const { return Get() + GetSize(); }
  PTRTYPE *begin() { return Get(); }
  PTRTYPE *end() { return Get() + GetSize(); }

private:
  PTRTYPE *m_sb;
};

template<class PTRTYPE, int SZ> struct WDL_TypedArray
{
  PTRTYPE *Get() { return m_sb; }
  const PTRTYPE *Get() const { return m_sb; }
  int GetSize() const { return SZ; }
  int GetSizeBytes() const { return (int)sizeof(m_sb); }
  void SetToZero() { memset(m_sb, 0, GetSizeBytes()); }
  PTRTYPE *GetAligned(int align) const { return (PTRTYPE *)(((UINT_PTR)Get() + (align-1)) & ~(UINT_PTR)(align-1)); }

  int Find(PTRTYPE val) const
  {
    for (int i = 0; i < SZ; i++) if (m_sb[i] == val) return i;
    return -1;
  }

  const PTRTYPE *begin() const { return Get(); }
  const PTRTYPE *end() const { return Get() + GetSize(); }
  PTRTYPE *begin() { return Get(); }
  PTRTYPE *end() { return Get() + GetSize(); }

  PTRTYPE m_sb[SZ];
};

#endif // _WDL_AGGARRAY_H_
