#ifndef ITERABLE_H
#define ITERABLE_H


#include <dump.h>
#include <stdlib.h>
#include <string.h>


#define foreach(item, items)    for (int i = items.count() - 1, j = 1; i >= 0; i--, j = 1) \
                                    for (item = items[i]; j; j = 0)


template<typename T>
class Iterable : public Dumpable
{
public:
    Iterable() : items(0), cnt(0) {
//        printf("Default Constructor\n");
    }
    Iterable(const Iterable<T> &cpy) : items(0) {
//        printf("Copy Constructor\n");
        copy(cpy);
    }
    virtual ~Iterable() {
//        printf("Destructor\n");
        if (items)
            free(items);
    }
    const Iterable& operator=(const Iterable& cpy) {
//        printf("Copy Assignment\n");
        copy(cpy);
        return *this;
    }
    void copy(const Iterable& copy) {
        items = (T*)realloc(items, sizeof(T) * copy.cnt);
        memcpy(items, copy.items, sizeof(T) * copy.cnt);
        cnt = copy.cnt;
    }

    const char *className() const { return "Iterable<T>"; }
    const char *dump() const { return "{ 0, 0, 0 }"; }

    T &operator[](int);
    const T &operator[](int) const;
    int count() const;
protected:
    T *items;
    int cnt;
};


#include <iterable_impl.h>


#endif // ITERABLE_H

