cache2.h 29.3 KB
Newer Older
Damien Leroux's avatar
Damien Leroux committed
1
2
3
4
5
6
7
8
9
10
#ifndef _SPEL_CACHE_2_H_
#define _SPEL_CACHE_2_H_

#include <future>
#include <tuple>
#include <unordered_map>
#include <iostream>
#include <string>
#include <sstream>

11
12
13
14
15

enum CachingPolicy : int { Oneshot = 0, Mem = 1, Disk = 2, Sync = 4 };
constexpr CachingPolicy operator | (CachingPolicy c1, CachingPolicy c2) { return CachingPolicy(int(c1) | int(c2)); }
constexpr CachingPolicy operator & (CachingPolicy c1, CachingPolicy c2) { return CachingPolicy(int(c1) & int(c2)); }

Damien Leroux's avatar
Damien Leroux committed
16
17
18
19
20
#include "error.h"
#include "input.h"
#include "cache/md5.h"
#include "cache/file.h"

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
extern "C" {
#include <dlfcn.h>
#include <malloc.h>
#include <string.h>
}
#include <cxxabi.h>

/*
char*
__cxa_demangle(const char* __mangled_name, char* __output_buffer, size_t* __length, int* __status);
*/

/*using demangle = abi::__cxa_demangle;*/

static inline
std::unordered_map<void*, std::string>&
demangled_names_registry()
{
	static std::unordered_map<void*, std::string> _;
	return _;
}


template <typename Ret, typename... Args>
std::string&
get_func_name(Ret (*f) (Args...))
{
	union {
		Ret (*fptr) (Args...);
		void* vptr;
	} tmp = {f};
	std::string& ret = demangled_names_registry()[tmp.vptr];
	if (!ret.size()) {
		Dl_info info;
		dladdr(tmp.vptr, &info);
		int status = 0;
		char* buf = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
		ret.assign(buf, strchr(buf, '('));
		free(buf);
		/*std::cout << tmp.vptr << " => " << info.dli_sname << std::endl;*/
	}
	return ret;
}


template <typename Ret, typename... Args>
std::string&
get_func_name(Ret (&f) (Args...))
{
	return get_func_name(&f);
}


Damien Leroux's avatar
Damien Leroux committed
74
75
76
77
78
79
80
81
/* forward */ struct md5_digest;

template <typename X> struct clean_type { typedef typename std::remove_reference<X>::type type; };
template <typename X> struct clean_type<const X&> { typedef X type; };
template <typename X> struct clean_type<X&> { typedef X type; };
template <typename X> struct clean_type<const X> { typedef X type; };


82
static inline std::string& cache_directory() { return active_settings->work_directory; }
Damien Leroux's avatar
Damien Leroux committed
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

template <typename T> struct generic_value_interface;
template <typename T> struct value;
template <typename T> struct range;
template <typename T> struct collection;

template <typename T> struct fail : std::integral_constant<bool, false> {};

template <typename T> struct value<collection<T>> { static_assert(fail<T>::value, "Can't instantiate this"); };


template <typename T> struct immediate_value;

template <typename FuncType> struct async_computation;
template <typename FuncType> struct cached_computation;
template <typename FuncType> struct computed_value_factory;
template <typename FuncType> struct computed_value;
template <typename FuncType> struct cached_computed_value;

/* a value<T> behaves as a pointer to T */

template <typename T>
    struct generic_value_interface {
        typedef T value_type;

        virtual ~generic_value_interface() {}

        virtual value_type& operator * () = 0;
        virtual value_type* operator -> () = 0;

        virtual const value_type& operator * () const = 0;
        virtual const value_type* operator -> () const = 0;

        virtual size_t hash() const = 0;
        virtual md5_digest& md5(md5_digest&) const = 0;
        virtual bool equal(const generic_value_interface<T>&) const { return false; }
        virtual bool __equal__(const T&) const { return false; }
    };

/* Lightweight */
template <typename T>
    struct value {
        typedef T value_type;

        value() : m_impl() {}
        value(generic_value_interface<T>* v) : m_impl(v) {}
        value(const T& immed) : m_impl(new immediate_value<T>(immed)) {}
        value(T&& immed) : m_impl(new immediate_value<T>(std::forward<T>(immed))) {}

        value_type& operator * () { return m_impl->operator * (); }
        value_type* operator -> () { return m_impl->operator -> (); }
        const value_type& operator * () const { return m_impl->operator * (); }
        const value_type* operator -> () const { return m_impl->operator -> (); }
        size_t hash() const { return m_impl->hash(); }
        md5_digest& md5(md5_digest& md) const { return m_impl->md5(md); }

        value<T> operator = (const T& immed)
        {
            /*m_impl = new immediate_value<T>(immed);*/
            m_impl = std::make_shared<immediate_value<T>>(immed);
            return *this;
        }

        value<T> operator = (std::shared_ptr<generic_value_interface<T>>& new_impl)
        {
            m_impl = new_impl;
            return *this;
        }

        value<T> operator = (const value<T>& new_impl)
        {
            m_impl = new_impl.m_impl;
            return *this;
        }

        bool valid() const { return (bool) m_impl; }

160
161
		operator bool () const { return valid(); }

Damien Leroux's avatar
Damien Leroux committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
        bool equal(const value<T>& v) const { return m_impl == v.m_impl || m_impl->equal(*v.m_impl); }

    protected:
        std::shared_ptr<generic_value_interface<T>> m_impl;
    };

template <typename T>
bool operator == (const value<T>& v1, const value<T>& v2) { return v1.equal(v2); }

namespace std {
    template <typename T>
        struct hash<value<T>> {
            size_t operator () (const value<T>& v) const
            {
                return v.hash();
            }
        };
}

template <typename VT>
std::ostream& operator << (std::ostream& os, const value<VT>& v)
{
    return os << (*v);
}

template <typename VT>
md5_digest& operator << (md5_digest& md5, const value<VT>& v)
{
    return v.md5(md5);
}


struct md5_hash_type {
    std::string accum;
    std::string append;
};


namespace redux {
template <typename Functor, typename... Elems> struct reduce_impl;

template <typename Functor, typename Elem>
    struct reduce_impl<Functor, Elem> {
        template <typename accum_type>
        void operator () (Functor& f, accum_type& accum, const Elem& e)
        {
            /*std::cout << "final e=" << e << std::endl;*/
            f(accum, e);
        }
    };

template <typename Functor, typename Elem, typename... Elems>
    struct reduce_impl<Functor, Elem, Elems...> {
        template <typename accum_type>
        void operator () (Functor& f, accum_type& accum, const Elem& e, const Elems&... x)
        {
            /*std::cout << "e=" << e << std::endl;*/
            f(accum, e);
            reduce_impl<Functor, Elems...>()(f, accum, x...);
        }
    };

struct reduce {
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    template <typename Functor>
        auto operator () (typename Functor::accum_type accum, Functor&)
            -> typename Functor::accum_type
        {
            return accum;
        }

    template <typename Functor>
        auto operator () (Functor&)
            -> typename Functor::accum_type
        {
            return typename Functor::accum_type();
        }

Damien Leroux's avatar
Damien Leroux committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    template <typename Functor, typename... Elems>
        auto operator () (typename Functor::accum_type accum, Functor& f, const Elems&... e)
            -> typename Functor::accum_type
        {
            reduce_impl<Functor, Elems...>()(f, accum, e...);
            return accum;
        }

    template <typename Functor, typename... Elems>
        auto operator () (Functor& f, const Elems&... e)
            -> typename Functor::accum_type
        {
            typename Functor::accum_type accum = typename Functor::accum_type();
            reduce_impl<Functor, Elems...>()(f, accum, e...);
            return accum;
        }
};

struct hash {
    typedef size_t accum_type;
    template <typename T>
        void operator () (size_t accum, const T& t) { accum = accum ^ std::hash<T>()(t); }
    template <typename VT>
        void operator () (size_t accum, const value<VT>& v) { accum = accum ^ v.hash(); }
};

struct md5 {
    typedef md5_digest& accum_type;
    template <typename T>
        void operator () (md5_digest& md, const T& t) { md << t; }
    template <typename VT>
        void operator () (md5_digest& md, const value<VT>& v) { v.md5(md); }
};

struct md5_append {
    typedef std::stringstream& accum_type;
    template <typename T>
        void operator () (std::stringstream& ss, const T& t)
        {
            md5_digest md;
            md << t;
            ss << (std::string) md;
        }
    template <typename VT>
        void operator () (std::stringstream& ss, const value<VT>& t)
        {
            md5_digest md;
            ss << (std::string) t.md5(md);
        }
};
} /* namespace redux */

template <typename... Elems>
size_t compute_hash(const Elems&... e) { redux::hash h; return redux::reduce()(0, h, e...); }

template <typename... Elems>
std::string compute_md5(const Elems&... e)
{
    md5_digest md;
    redux::md5 m;
    redux::reduce()(md, m, e...);
    return md;
}

template <typename... Elems>
std::string append_md5(const Elems&... e) { std::stringstream ss; redux::md5_append ma; return redux::reduce()(ss, ma, e...).str(); }


template <typename ValueType>
    struct immediate_value : generic_value_interface<ValueType> {
        typedef ValueType value_type;

        value_type m_storage;

        immediate_value(const ValueType& v) : m_storage(v) {}
        immediate_value(ValueType&& v) : m_storage(std::forward<ValueType>(v)) {}
315
316
        template <typename... Args>
            immediate_value(Args... x) : m_storage(x...) {}
Damien Leroux's avatar
Damien Leroux committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

        virtual
            value_type& operator * ()
            override { return m_storage; }
        virtual
            value_type* operator -> ()
            override { return &m_storage; }
        virtual
            const value_type& operator * () const
            override { return m_storage; }
        virtual
            const value_type* operator -> () const
            override { return &m_storage; }

        virtual
            size_t hash() const
            override { return std::hash<ValueType>()(m_storage); }
        virtual
            md5_digest& md5(md5_digest& md) const
            override { return md << m_storage; }

        virtual
            bool equal(const generic_value_interface<ValueType>& gvi) const
            override
            {
                return gvi.__equal__(m_storage);
            }

        virtual
            bool __equal__(const ValueType& v) const
            override
            {
                return m_storage == v;
            }
    };


template <typename ValueType>
    struct unique_value : generic_value_interface<ValueType> {
        typedef ValueType value_type;

        value_type m_storage;

        unique_value(const ValueType& v) : m_storage(v) {}
        unique_value(ValueType&& v) : m_storage(std::forward<ValueType>(v)) {}
        unique_value() : m_storage() {}

        virtual
            value_type& operator * ()
            override { return m_storage; }
        virtual
            value_type* operator -> ()
            override { return &m_storage; }
        virtual
            const value_type& operator * () const
            override { return m_storage; }
        virtual
            const value_type* operator -> () const
            override { return &m_storage; }

        virtual
            size_t hash() const
            override { return std::hash<const void*>()(this); }
        virtual
            md5_digest& md5(md5_digest& md) const
            override { return md << m_storage; }
    };

/*template <typename M, typename R, typename C>*/
    /*struct immediate_value<labelled_matrix<M, R, C>>*/
        /*: unique_value<labelled_matrix<M, R, C>> {};*/



template <typename Ret, typename... Args>
    struct async_computation<Ret(Args...)> {
        typedef async_computation<Ret(Args...)> this_type;
        typedef Ret value_type;
        typedef Ret (*computation_function_pointer_type) (Args...);
        typedef std::packaged_task<Ret(Args...)> task_type;

398
        async_computation(CachingPolicy _Sync, computation_function_pointer_type func,
Damien Leroux's avatar
Damien Leroux committed
399
400
401
                          const value<typename clean_type<Args>::type>&... args)
            : dependencies(args...)
            , m_storage()
402
            , m_future(active_settings->enqueue(_Sync, func, *args...))
403
404
            /*, m_future(std::async(std::launch::async, func, *args...))*/
            /*, m_future(std::async(std::launch::deferred, func, *args...))*/
405
            , mutex()
Damien Leroux's avatar
Damien Leroux committed
406
407
        {}

408
        async_computation(CachingPolicy _Sync, std::function<Ret(Args...)>& func,
Damien Leroux's avatar
Damien Leroux committed
409
410
411
                          const value<typename clean_type<Args>::type>&... args)
            : dependencies(args...)
            , m_storage()
412
            , m_future(active_settings->enqueue(_Sync, func, *args...))
413
            /*, m_future(std::async(func, *args...))*/
414
            , mutex()
Damien Leroux's avatar
Damien Leroux committed
415
416
417
418
        {}

        value_type& __get_noconst()
        {
419
            std::unique_lock<std::mutex> read_guard(mutex);
Damien Leroux's avatar
Damien Leroux committed
420
421
422
423
424
425
426
427
            if (m_future.valid()) {
                return m_storage = m_future.get();
            }
            return m_storage;
        }

        const value_type& __get_const() const
        {
428
            std::unique_lock<std::mutex> read_guard(*const_cast<std::mutex*>(&mutex));
Damien Leroux's avatar
Damien Leroux committed
429
430
431
432
433
434
435
            return const_cast<this_type*>(this)->__get_noconst();
        }

    protected:
        std::tuple<value<typename clean_type<Args>::type>...> dependencies;
        value_type m_storage;
        std::future<Ret> m_future;
436
        std::mutex mutex;
Damien Leroux's avatar
Damien Leroux committed
437
438
439
440
441
442
443
    };


template <typename Ret, typename... Args>
    struct cached_computation<Ret(Args...)> {
        typedef Ret value_type;

444
        cached_computation(const std::string& name, Ret (*f) (Args...), const value<typename clean_type<Args>::type>&... args)
Damien Leroux's avatar
Damien Leroux committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
            : m_name(name)
            , m_func(f)
            , m_md5_hash{.accum = compute_md5(args...), .append = append_md5(args...)}
        {}

        std::string get_path() const
        {
            std::stringstream ss;
            ss << cache_directory() << '/' << m_name << '_' << m_md5_hash.accum << '_' << typeid(Ret).name();
            return ss.str();
        }

        Ret operator () (Args... x)
        {
            Ret data;
            std::string path = get_path();
            /* if cache file found */
462
            if (check_file(path, false, true, false)) {
Damien Leroux's avatar
Damien Leroux committed
463
464
465
466
467
468
469
470
471
                std::ifstream ifs(path);
                cache_input ci(ifs);
                std::string check;
            /*   read string */
                ci & check;
            /*   compare to m_md5_hash.append */
                if (check == m_md5_hash.append) {
            /*   if same */
            /*     CACHE FOUND */
472
                    /*MSG_INFO("Found data in cache");*/
Damien Leroux's avatar
Damien Leroux committed
473
474
475
476
477
                    ci & data;
            /*     return value read from file */
                    return data;
                }
            /*   CACHE INVALID */
478
                /*MSG_INFO("Cache is invalid. Computing data.");*/
Damien Leroux's avatar
Damien Leroux committed
479
480
481
            } else {
            /* else */
            /*   COMPUTE AND SAVE */
482
                /*MSG_INFO("Computing data.");*/
Damien Leroux's avatar
Damien Leroux committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
            }
            /* compute value = m_func(x...) */
            data = m_func(x...);
            /* write m_md5_hash.append to file */
            std::ofstream ofs(path);
            cache_output co(ofs);
            co & m_md5_hash.append;
            /* write value to file */
            co & data;
            /* return value */
            return data;
        }

    protected:
        std::string m_name;
        Ret (*m_func) (Args...);
        md5_hash_type m_md5_hash;
    };


template <typename Ret, typename... Args>
    struct computed_value<Ret(Args...)> : generic_value_interface<Ret> {
        typedef Ret value_type;
        typedef std::function<Ret(Args...)> computation_type;

508
        computed_value(CachingPolicy _Sync, Ret (*func) (Args...), const value<typename clean_type<Args>::type>&... args)
Damien Leroux's avatar
Damien Leroux committed
509
            : m_hash(compute_hash(args...))
510
            , m_task(_Sync, func, args...)
Damien Leroux's avatar
Damien Leroux committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
        {}

        virtual
            value_type& operator * ()
            override { return m_task.__get_noconst(); }
        virtual
            value_type* operator -> ()
            override { return &m_task.__get_noconst(); }
        virtual
            const value_type& operator * () const
            override { return m_task.__get_const(); }
        virtual
            const value_type* operator -> () const
            override { return &m_task.__get_const(); }

        virtual
            size_t hash() const
            override { return m_hash; }
        virtual
            md5_digest& md5(md5_digest& md) const
            override { return md; }

    protected:
        size_t m_hash;
        async_computation<Ret(Args...)> m_task;
    };

template <typename Ret, typename... Args>
    struct cached_computed_value<Ret(Args...)> : generic_value_interface<Ret> {
        typedef Ret value_type;
        typedef std::function<Ret(Args...)> computation_type;

543
        cached_computed_value(CachingPolicy _Sync, Ret (*func) (Args...), const value<typename clean_type<Args>::type>&... args)
Damien Leroux's avatar
Damien Leroux committed
544
            : m_hash(compute_hash(args...))
545
            , m_comp(get_func_name(func), func, args...)
Damien Leroux's avatar
Damien Leroux committed
546
            , m_comp_proxy([this](Args... x) { return m_comp(x...); })
547
            , m_task(_Sync, m_comp_proxy, args...)
Damien Leroux's avatar
Damien Leroux committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
        {}

        virtual
            value_type& operator * ()
            override { return m_task.__get_noconst(); }
        virtual
            value_type* operator -> ()
            override { return &m_task.__get_noconst(); }
        virtual
            const value_type& operator * () const
            override { return m_task.__get_const(); }
        virtual
            const value_type* operator -> () const
            override { return &m_task.__get_const(); }

        virtual
            size_t hash() const
            override { return m_hash; }
        virtual
            md5_digest& md5(md5_digest& md) const
            override { return md; }

    protected:
        size_t m_hash;
        cached_computation<Ret(Args...)> m_comp;
        std::function<Ret(Args...)> m_comp_proxy;
        async_computation<Ret(Args...)> m_task;
    };


/* ranges and collections */

/* T must have operators + and < */
template <typename T>
    struct range {
        T m_min, m_max, m_step;
        range(T min, T max, T step)
            : m_min(min), m_max(max), m_step(step)
        {}
        struct iterator {
            value<T> m_data;
            T m_step;
            T m_max;
            iterator(T value, T max, T step)
                : m_data(new immediate_value<T>(value)), m_step(step), m_max(max)
            {}
            iterator& operator ++ ()
            {
                *m_data += m_step;
                if (*m_data > m_max) {
                    *m_data = m_max;
                }
                return *this;
            }
            bool operator == (const iterator& i) const
            {
                return *m_data == *i.m_data;
            }
            bool operator != (const iterator& i) const
            {
                return *m_data != *i.m_data;
            }
            const value<T>& operator * () const { return m_data; }
        };
        iterator begin() const { return {m_min, m_max, m_step}; }
        iterator end() const { return {m_max, m_max, 0}; }
    };


#if 0
template <typename ValueType, typename... AllArgs> struct registry_impl_type;
template <typename ValueType>
    struct registry_impl_type<ValueType> { typedef ValueType type; };
template <typename ValueType, typename Arg0, typename... OtherArgs>
    struct registry_impl_type<ValueType, Arg0, OtherArgs...> {
        typedef std::unordered_map<Arg0, registry_impl_type<ValueType, OtherArgs...>::type> type;
    };
#endif

template <typename ValueType, typename... AllArgs>
struct computation_registry {
    typedef ValueType value_type;

    template <typename... Args> struct registry_impl;

    template <typename Arg0>
        struct registry_impl<Arg0> {
            std::unordered_map<Arg0, value_type> m_registry;
            value_type& get_(const Arg0& arg)
            {
                return m_registry[arg];
            }

            size_t size() const { return m_registry.size(); }
        };

    template <typename Arg0, typename... Args>
        struct registry_impl<Arg0, Args...> {
            std::unordered_map<Arg0, registry_impl<Args...>> m_registry;
            value_type& get_(const Arg0& car, const Args&... cdr)
            {
                return m_registry[car].get_(cdr...);
            }

            size_t size() const
            {
                size_t accum = 0;
                for (auto& kv: m_registry) {
                    accum += kv.second.size();
                }
                return accum;
            }
        };

    registry_impl<AllArgs...> m_registry;

    template <typename... Args>
        value_type& get(const Args&... args)
        {
            return m_registry.get_(args...);
        }

    size_t size() const { return m_registry.size(); }
};


template <typename Ret, typename... Args>
computation_registry<value<Ret>, Ret (*) (Args...), value<typename clean_type<Args>::type>...>&
__get_registry()
{
    static computation_registry<value<Ret>, Ret (*) (Args...), value<typename clean_type<Args>::type>...> _reg_;
    /*MSG_DEBUG("Registry at " << (&_reg_));*/
    return _reg_;
}

683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#if 0
static inline
std::mutex& __get_lock(void* fptr)
{
    struct m_wrap { std::mutex mutex; m_wrap() : mutex() {} m_wrap(const m_wrap&) : mutex() {} };
    static std::unordered_map<void*, m_wrap> _;
    return _[fptr].mutex;
    /*auto it = _.find(fptr);*/
    /*if (it == _.end()) {*/
        /*bool discard;*/
        /*std::tie(it, discard) = _.insert({fptr, {}});*/
    /*}*/
    /*return it->second;*/
}
#endif
Damien Leroux's avatar
Damien Leroux committed
698
699
700
701
702
703

template <typename VT>
using clean_value_type = value<typename clean_type<VT>::type>;


template <typename Ret, typename... Args>
704
705
706
struct with_disk_cache_traits {
	typedef cached_computed_value<Ret(Args...)> type;
};
Damien Leroux's avatar
Damien Leroux committed
707
708

template <typename Ret, typename... Args>
709
710
711
struct without_disk_cache_traits {
	typedef computed_value<Ret(Args...)> type;
};
Damien Leroux's avatar
Damien Leroux committed
712

713
714
template <int _Policy, typename Ret, typename... Args>
struct disk_cache_traits;
Damien Leroux's avatar
Damien Leroux committed
715

716
template <typename Ret, typename... Args>
717
struct disk_cache_traits<Oneshot, Ret, Args...> : without_disk_cache_traits<Ret, Args...> {};
718
719

template <typename Ret, typename... Args>
720
struct disk_cache_traits<Disk, Ret, Args...> : with_disk_cache_traits<Ret, Args...> {};
Damien Leroux's avatar
Damien Leroux committed
721

722
723
724
725
726
727
728
template <typename Ret, typename... Args>
struct with_mem_cache_traits {
	typedef value<Ret>& return_type;

	template <typename _Maker>
		static
		return_type
729
		create(CachingPolicy _Sync, Ret (&f) (Args...), const clean_value_type<Args>&... x)
730
		{
731
732
            static std::mutex _;
            std::unique_lock<std::mutex> lock_guard(_);
733
734
735
			/*MSG_DEBUG("new value with mem cache");*/
			return_type ret = __get_registry<Ret, Args...>().get(&f, x...);
			if (!ret.valid()) {
736
				ret = new _Maker(_Sync, f, x...);
737
738
739
740
741
742
743
744
745
746
747
748
			}
			return ret;
		}
};

template <typename Ret, typename... Args>
struct without_mem_cache_traits {
	typedef value<Ret> return_type;

	template <typename _Maker>
		static
		return_type
749
		create(CachingPolicy _Sync, Ret (&f) (Args...), const clean_value_type<Args>&... x)
750
751
		{
			/*MSG_DEBUG("new value without mem cache");*/
752
			return_type ret = new _Maker(_Sync, f, x...);
753
754
755
756
757
758
759
760
			return ret;
		}
};

template <int _Policy, typename Ret, typename... Args>
struct mem_cache_traits;

template <typename Ret, typename... Args>
761
struct mem_cache_traits<Oneshot, Ret, Args...> : without_mem_cache_traits<Ret, Args...> {};
762
763

template <typename Ret, typename... Args>
764
struct mem_cache_traits<Mem, Ret, Args...> : with_mem_cache_traits<Ret, Args...> {};
765

766
767
template <CachingPolicy _Policy = Oneshot, typename Ret, typename... Args>
typename mem_cache_traits<_Policy & Mem, Ret, Args...>::return_type
768
769
make_value(Ret (&f) (Args...), const clean_value_type<Args>&... x)
{
770
771
772
	typedef mem_cache_traits<_Policy & Mem, Ret, Args...> mem_policy;
	typedef disk_cache_traits<_Policy & Disk, Ret, Args...> disk_policy;
	return mem_policy::template create<typename disk_policy::type>(_Policy & Sync, f, x...);
773
}
Damien Leroux's avatar
Damien Leroux committed
774
775
776

template <typename T> struct collection : std::vector<value<T>> {
    using std::vector<value<T>>::vector;
777
778
779
780
781
782
783
784
785
    using std::vector<value<T>>::operator [];
    template <typename INTEGRAL_TYPE>
        value<T>&
        operator [] (const value<INTEGRAL_TYPE>& i)
        { return (*this)[*i]; }
    template <typename INTEGRAL_TYPE>
        const value<T>&
        operator [] (const value<INTEGRAL_TYPE>& i) const
        { return (*this)[*i]; }
Damien Leroux's avatar
Damien Leroux committed
786
787
};

788
789
template <typename... X> struct tuple;

790
template <CachingPolicy C, typename F, typename R, typename P> struct make_coll_impl;
Damien Leroux's avatar
Damien Leroux committed
791
792
793
794
795
796
797
798
799
800

template <typename A, typename B> struct types_must_be_identical : std::integral_constant<bool, false> {};
template <> struct types_must_be_identical<int, double> : std::integral_constant<bool, false> {};
template <> struct types_must_be_identical<double, int> : std::integral_constant<bool, false> {};
template <typename A> struct types_must_be_identical<A, A> : std::integral_constant<bool, true> {};
template <typename A> struct types_must_be_identical<const A&, A> : std::integral_constant<bool, true> {};
template <typename A> struct types_must_be_identical<A&, A> : std::integral_constant<bool, true> {};
template <typename A> struct types_must_be_identical<const A, A> : std::integral_constant<bool, true> {};

template <typename LA, typename LB> struct type_lists_must_be_identical;
801
template <> struct type_lists_must_be_identical<tuple<>, tuple<>> {};
Damien Leroux's avatar
Damien Leroux committed
802
803

template <typename A0, typename... A, typename B0, typename... B>
804
805
    struct type_lists_must_be_identical<tuple<A0, A...>, tuple<B0, B...>>
            : type_lists_must_be_identical<tuple<A...>, tuple<B...>> {
Damien Leroux's avatar
Damien Leroux committed
806
807
808
        static_assert(types_must_be_identical<A0, B0>::value, "INVALID PARAMETER TYPE.");
    };

809
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename... ErrArgs>
810
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<>, tuple<ErrArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
811
812
813
814
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      ErrArgs... errargs)
    {
815
        type_lists_must_be_identical<tuple<FuncArgs...>, tuple<typename ErrArgs::value_type...>>();
816
        coll.push_back(make_value<_Policy>(f, errargs...));
Damien Leroux's avatar
Damien Leroux committed
817
818
819
    }
};

820
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs>
821
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<>, tuple<clean_value_type<FuncArgs>...>> {
Damien Leroux's avatar
Damien Leroux committed
822
823
824
825
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      const value<typename clean_type<FuncArgs>::type>&... pargs)
    {
826
        coll.push_back(make_value<_Policy>(f, pargs...));
Damien Leroux's avatar
Damien Leroux committed
827
828
829
830
    }
};


831
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename VT, typename... ArgsRemaining, typename... PreviousArgs>
832
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<value<VT>, ArgsRemaining...>, tuple<PreviousArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
833
834
835
836
837
838
839
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      const value<VT>& car,
                      const ArgsRemaining&... cdr,
                      const PreviousArgs&... pargs)
    {
        make_coll_impl<
840
			_Policy,
Damien Leroux's avatar
Damien Leroux committed
841
            Ret(FuncArgs...),
842
843
            tuple<ArgsRemaining...>,
            tuple<PreviousArgs..., value<VT>>>() (coll, f, cdr..., pargs..., car);
Damien Leroux's avatar
Damien Leroux committed
844
845
846
    }
};

847
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename T, typename... ArgsRemaining, typename... PreviousArgs>
848
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<range<T>, ArgsRemaining...>, tuple<PreviousArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
849
850
851
852
853
854
855
856
857
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      const range<T>& car,
                      const ArgsRemaining&... cdr,
                      const PreviousArgs&... pargs)
    {
        typedef value<T> vtype;
        for (const vtype& v: car) {
            make_coll_impl<
858
				_Policy,
Damien Leroux's avatar
Damien Leroux committed
859
                Ret(FuncArgs...),
860
861
                tuple<ArgsRemaining...>,
                tuple<PreviousArgs..., vtype>>() (coll, f, cdr..., pargs..., v);
Damien Leroux's avatar
Damien Leroux committed
862
863
864
865
        }
    }
};

866
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename T, typename... ArgsRemaining, typename... PreviousArgs>
867
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<collection<T>, ArgsRemaining...>, tuple<PreviousArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
868
869
870
871
872
873
874
875
876
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      const collection<T>& car,
                      const ArgsRemaining&... cdr,
                      const PreviousArgs&... pargs)
    {
        typedef value<T> vtype;
        for (const vtype& v: car) {
            make_coll_impl<
877
				_Policy,
Damien Leroux's avatar
Damien Leroux committed
878
                Ret(FuncArgs...),
879
880
                tuple<ArgsRemaining...>,
                tuple<PreviousArgs..., vtype>>() (coll, f, cdr..., pargs..., v);
Damien Leroux's avatar
Damien Leroux committed
881
882
883
884
885
886
        }
    }
};



887
template <CachingPolicy _Policy = Oneshot, typename Ret, typename... Args, typename... CollArgs>
Damien Leroux's avatar
Damien Leroux committed
888
889
890
891
collection<Ret>
make_collection(Ret (&f) (Args...), CollArgs... args)
{
    collection<Ret> ret;
892
    make_coll_impl<_Policy, Ret(Args...), tuple<CollArgs...>, tuple<>>() (ret, f, args...);
Damien Leroux's avatar
Damien Leroux committed
893
894
895
896
    return ret;
}


897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936

template <typename T1, typename T2>
std::ostream& operator << (std::ostream& os, const std::pair<T1, T2>& p) { return os << p.first << ':' << p.second; }

template <typename T1, typename T2>
std::ostream& operator << (std::ostream& os, const std::map<T1, T2>& m)
{
    auto i = m.begin(), j = m.end();
    os << '{';
    if (i != j) {
        os << (*i);
        for (++i; i != j; ++i) {
            os << ' ' << (*i);
        }
    }
    return os << '}';
}



template <typename T>
std::ostream&
operator << (std::ostream& os, const collection<T>& coll)
{
    for (const auto& k: coll) {
        os << '\t' << k << std::endl;
    }
#if 0
    auto i = coll.begin(), j = coll.end();
    if (i == j) {
        return os;
    }
    os << (**i);
    for (++i; i != j; ++i) {
        os << ' ' << (**i);
    }
#endif
    return os;
}

Damien Leroux's avatar
Damien Leroux committed
937
938
#endif