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

#include <future>
#include <tuple>
#include <unordered_map>
#include <iostream>
#include <string>
#include <sstream>
10
11
#include "function_wrapper.h"
#include "chrono.h"
Damien Leroux's avatar
Damien Leroux committed
12

13

14
15
16
17
18
19
20
21


struct chrono_trace {
    const std::string& name;
    chrono_trace(const std::string& n) : name(n) { chrono::increment(name); chrono::start(name); }
    ~chrono_trace() { chrono::stop(name); }
};

22
23
24
25
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)); }

26
27
28
29
30
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; };

Damien Leroux's avatar
Damien Leroux committed
31
32
33
34
#include "error.h"
#include "input.h"
#include "cache/md5.h"
#include "cache/file.h"
35
#include "cache/registry.h"
Damien Leroux's avatar
Damien Leroux committed
36

37
extern "C" {
38
/*#include <dlfcn.h>*/
39
#include <malloc.h>
40
/*#include <string.h>*/
41
}
42
/*#include <cxxabi.h>*/
43
44
45
46
47
48
49
50

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

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

51
#if 0
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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);
}
89
#endif
90

Damien Leroux's avatar
Damien Leroux committed
91
92
93
/* forward */ struct md5_digest;


94
static inline std::string& cache_directory() { return active_settings->work_directory; }
Damien Leroux's avatar
Damien Leroux committed
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

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;
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146

        bool operator == (const generic_value_interface<T>& gvi) const
        {
            return **this == *gvi;
        }
#if 0
        /*virtual bool equal(const generic_value_interface<T>&) const { return false; }*/
        virtual
            bool equal(const generic_value_interface<T>& gvi) const
            /*override*/
            {
                return **this == *gvi;
                /*return gvi.__equal__(m_storage);*/
            }

        /*virtual bool __equal__(const T&) const = 0;  // { return false; }*/
#endif
Damien Leroux's avatar
Damien Leroux committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    };

/* 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); }

166
        value<T>& operator = (const T& immed)
Damien Leroux's avatar
Damien Leroux committed
167
168
169
170
171
172
        {
            /*m_impl = new immediate_value<T>(immed);*/
            m_impl = std::make_shared<immediate_value<T>>(immed);
            return *this;
        }

173
        value<T>& operator = (std::shared_ptr<generic_value_interface<T>>& new_impl)
Damien Leroux's avatar
Damien Leroux committed
174
175
176
177
178
        {
            m_impl = new_impl;
            return *this;
        }

179
        value<T>& operator = (const value<T>& new_impl)
Damien Leroux's avatar
Damien Leroux committed
180
181
182
183
184
185
186
        {
            m_impl = new_impl.m_impl;
            return *this;
        }

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

187
188
		operator bool () const { return valid(); }

189
190
        /*bool equal(const value<T>& v) const { return m_impl == v.m_impl || m_impl->equal(*v.m_impl); }*/
        bool equal(const value<T>& v) const { return m_impl == v.m_impl || *m_impl == *v.m_impl; }
Damien Leroux's avatar
Damien Leroux committed
191
192
193
194
195
196
197
198

    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); }

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

202
203
204
205
206

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


Damien Leroux's avatar
Damien Leroux committed
207
208
209
210
211
212
213
214
namespace std {
    template <typename T>
        struct hash<value<T>> {
            size_t operator () (const value<T>& v) const
            {
                return v.hash();
            }
        };
215
216
217
218
219
220
221
222
223
224

    template <typename T>
        struct hash<collection<T>> {
            size_t operator () (const collection<T>& c) const
            {
                md5_digest h;
                h.update(c.begin(), c.end());
                return h.context;
            }
        };
Damien Leroux's avatar
Damien Leroux committed
225
226
227
228
229
}

template <typename VT>
std::ostream& operator << (std::ostream& os, const value<VT>& v)
{
230
231
232
233
234
    if (v.valid()) {
        return os << (*v);
    } else {
        return os << "<nil>";
    }
Damien Leroux's avatar
Damien Leroux committed
235
236
237
238
239
240
241
242
243
244
}

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


struct md5_hash_type {
245
    md5_digest md5;
Damien Leroux's avatar
Damien Leroux committed
246
247
248
249
250
251
    std::string accum;
    std::string append;
};



252
#define do_with_arg_pack(_expr) do { using _ = int[]; (void)_{0, ((_expr), void(), 0)...}; } while(0)
Damien Leroux's avatar
Damien Leroux committed
253

254
255
namespace new_redux {
    /* pattern found on http://stackoverflow.com/a/19098481 */
Damien Leroux's avatar
Damien Leroux committed
256

257
258
    template <typename... Args>
        size_t hash(Args... args)
259
        {
260
261
262
263
            size_t accum = 0;
            do_with_arg_pack(accum ^= std::hash<Args>()(args));
            /*using apply_to_pack = int[];*/
            /*(void)apply_to_pack{0, (accum ^= std::hash<Args>()(args), void(), 0)...};*/
264
265
266
            return accum;
        }

267
268
    template <typename... Args>
        md5_digest feed_md5(Args... args)
269
        {
270
271
272
            md5_digest m;
            do_with_arg_pack(m << args);
            return m;
273
274
        }

275
276
    template <typename... Args>
        std::string md5(Args... args)
Damien Leroux's avatar
Damien Leroux committed
277
        {
278
279
            /*do_with_arg_pack(std::cout << args << std::endl);*/
            return feed_md5(args...);
Damien Leroux's avatar
Damien Leroux committed
280
281
        }

282
283
    template <typename... Args>
        std::string md5_append(Args... args)
Damien Leroux's avatar
Damien Leroux committed
284
        {
285
286
287
288
            std::stringstream s;
            do_with_arg_pack(s << md5(args));
            /*std::cout << "* Long MD5 " << s.str() << std::endl;*/
            return s.str();
Damien Leroux's avatar
Damien Leroux committed
289
290
        }

291
}
Damien Leroux's avatar
Damien Leroux committed
292
293

template <typename... Elems>
294
295
296
297
298
size_t compute_hash(const Elems&... e)
{
    /*redux::hash h; return redux::reduce()(0, h, e...);*/
    return new_redux::hash(e...);
}
Damien Leroux's avatar
Damien Leroux committed
299
300
301
302

template <typename... Elems>
std::string compute_md5(const Elems&... e)
{
303
304
305
306
307
    /*md5_digest md;*/
    /*redux::md5 m;*/
    /*redux::reduce()(md, m, e...);*/
    /*return md;*/
    return new_redux::md5(e...);
Damien Leroux's avatar
Damien Leroux committed
308
309
310
}

template <typename... Elems>
311
312
313
314
315
std::string append_md5(const Elems&... e)
{
    /*std::stringstream ss; redux::md5_append ma; return redux::reduce()(ss, ma, e...).str();*/
    return new_redux::md5_append(e...);
}
Damien Leroux's avatar
Damien Leroux committed
316
317
318
319
320
321
322
323
324
325


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)) {}
326
327
        template <typename... Args>
            immediate_value(Args... x) : m_storage(x...) {}
Damien Leroux's avatar
Damien Leroux committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347

        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; }
348
#if 0
Damien Leroux's avatar
Damien Leroux committed
349
350
351
352
353
354
        virtual
            bool __equal__(const ValueType& v) const
            override
            {
                return m_storage == v;
            }
355
#endif
Damien Leroux's avatar
Damien Leroux committed
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
    };


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>> {};*/


395
396
397
398
399
400
401
402
403
404
405
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_;
}


template <typename Ret, typename... Args>
406
407
408
409
410
411
    struct async_computation<Ret(Args...)>;

template <typename Ret, typename... Args>
computation_registry<std::shared_ptr<async_computation<Ret(Args...)>>,
                     Ret (*) (Args...),
                     value<typename clean_type<Args>::type>...>&
412
413
__get_in_progress_registry()
{
414
415
416
    static computation_registry<std::shared_ptr<async_computation<Ret(Args...)>>,
                                Ret (*) (Args...),
                                value<typename clean_type<Args>::type>...> _reg_;
417
418
419
420
421
422
423
424
425
    /*MSG_DEBUG("Registry at " << (&_reg_));*/
    return _reg_;
}


template <typename Ret, typename... Args>
std::mutex& __get_in_progress_mutex() { static std::mutex _; return _; }

template <typename Ret, typename... Args>
426
427
428
void
unregister_task_in_progress(Ret (*f) (Args...),
                            const value<typename clean_type<Args>::type>&... args)
429
430
{
    __get_in_progress_mutex<Ret, Args...>().lock();
431
    __get_in_progress_registry<Ret, Args...>().remove(f, args...);
432
433
434
435
436
    __get_in_progress_mutex<Ret, Args...>().unlock();
}


template <typename Ret, typename... Args>
437
438
439
440
std::shared_ptr<async_computation<Ret(Args...)>>
register_task_in_progress(std::shared_ptr<async_computation<Ret(Args...)>> v,
                          Ret (*f) (Args...),
                          const value<typename clean_type<Args>::type>&... args)
441
{
Damien Leroux's avatar
Damien Leroux committed
442
    /*__get_in_progress_mutex<Ret, Args...>().lock();*/
443
    __get_in_progress_registry<Ret, Args...>().get(f, args...) = v;
Damien Leroux's avatar
Damien Leroux committed
444
    /*__get_in_progress_mutex<Ret, Args...>().unlock();*/
445
    return v;
446
447
}

Damien Leroux's avatar
Damien Leroux committed
448
449
450
451
452
453
454
455

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;

456
        async_computation(CachingPolicy _Sync, computation_function_pointer_type func,
Damien Leroux's avatar
Damien Leroux committed
457
458
459
                          const value<typename clean_type<Args>::type>&... args)
            : dependencies(args...)
            , m_storage()
460
461
462
463
464
465
            , m_future(active_settings
                        ->enqueue(_Sync,
                            [=] (Args... args)
                            {
                                chrono_trace _(get_func_name(func));
                                Ret ret = func(args...);
466
                                unregister_task_in_progress(func, {args}...);
467
468
                                return ret;
                            }, *args...))
469
            , mutex()
470
        {  }
Damien Leroux's avatar
Damien Leroux committed
471

472
        async_computation(CachingPolicy _Sync, std::function<Ret(Args...)>& func,
Damien Leroux's avatar
Damien Leroux committed
473
474
475
                          const value<typename clean_type<Args>::type>&... args)
            : dependencies(args...)
            , m_storage()
476
            , m_future(active_settings->enqueue(_Sync, func, *args...))
477
            /*, m_future(std::async(func, *args...))*/
478
            , mutex()
Damien Leroux's avatar
Damien Leroux committed
479
480
481
482
        {}

        value_type& __get_noconst()
        {
Damien Leroux's avatar
Damien Leroux committed
483
484
485
486
487
            /*std::lock_guard<decltype(mutex)> read_guard(mutex);*/
            /*if (m_future.valid()) {*/
                /*return m_storage = m_future.get();*/
            /*}*/
            while (!mutex.try_lock());
Damien Leroux's avatar
Damien Leroux committed
488
            if (m_future.valid()) {
Damien Leroux's avatar
Damien Leroux committed
489
                m_storage = m_future.get();
Damien Leroux's avatar
Damien Leroux committed
490
            }
Damien Leroux's avatar
Damien Leroux committed
491
            mutex.unlock();
Damien Leroux's avatar
Damien Leroux committed
492
493
494
495
496
497
498
499
500
501
502
503
            return m_storage;
        }

        const value_type& __get_const() const
        {
            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;
Damien Leroux's avatar
Damien Leroux committed
504
        std::recursive_mutex mutex;
Damien Leroux's avatar
Damien Leroux committed
505
506
    };

507
508
509
510
511
512
template <typename Ret, typename... Args>
std::shared_ptr<async_computation<Ret(Args...)>>
    make_async_computation(CachingPolicy& _Sync,
                           Ret (*func) (Args...),
                           const value<typename clean_type<Args>::type>&... args)
    {
Damien Leroux's avatar
Damien Leroux committed
513
514
515
516
        struct _mac_guard {
            _mac_guard() { __get_in_progress_mutex<Ret, Args...>().lock(); }
            ~_mac_guard() { __get_in_progress_mutex<Ret, Args...>().unlock(); }
        } _;
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
        auto& r = __get_in_progress_registry<Ret, Args...>();
        auto exists = r.find(func, args...);
        if (exists) {
            return *exists;
        } else {
            std::shared_ptr<async_computation<Ret(Args...)>>
                ac(new async_computation<Ret(Args...)>(_Sync, func, args...));
            return r.get(func, args...) = register_task_in_progress(ac, func, args...);
        }
    }


template <typename Ret, typename... Args>
std::shared_ptr<async_computation<Ret(Args...)>>
    make_async_computation(CachingPolicy& _Sync,
                           Ret (*func) (Args...),
                           std::function<Ret(Args...)>& proxy,
                           const value<typename clean_type<Args>::type>&... args)
    {
Damien Leroux's avatar
Damien Leroux committed
536
537
538
539
        struct _mac_guard {
            _mac_guard() { __get_in_progress_mutex<Ret, Args...>().lock(); }
            ~_mac_guard() { __get_in_progress_mutex<Ret, Args...>().unlock(); }
        } _;
540
541
542
543
544
545
546
547
548
549
550
        auto& r = __get_in_progress_registry<Ret, Args...>();
        auto exists = r.find(func, args...);
        if (exists) {
            return *exists;
        } else {
            std::shared_ptr<async_computation<Ret(Args...)>>
                ac(new async_computation<Ret(Args...)>(_Sync, proxy, args...));
            return r.get(func, args...) = register_task_in_progress(ac, func, args...);
        }
    }

Damien Leroux's avatar
Damien Leroux committed
551
552
553
554
555

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

556
        cached_computation(const std::string& name, Ret (*f) (Args...), const value<typename clean_type<Args>::type>&... args)
Damien Leroux's avatar
Damien Leroux committed
557
558
            : m_name(name)
            , m_func(f)
559
560
561
562
563
564
565
566
567
568
569
570
            /*, m_md5_hash{.accum = compute_md5(args...), .append = append_md5(args...)}*/
        {
            m_md5_hash.md5 = new_redux::feed_md5(args...);
            m_md5_hash.accum = m_md5_hash.md5;
            m_md5_hash.append = new_redux::md5_append(args...);
            /*std::cout << "NEW CACHED_COMPUTATION WITH ARGS" << std::endl;*/
            /*do_with_arg_pack(std::cout << args << std::endl);*/
            /*std::cout << "================================" << std::endl;*/
            /*std::cout << m_md5_hash.accum << std::endl;*/
            /*std::cout << m_md5_hash.append << std::endl;*/
            /*std::cout << "NEW CACHED_COMPUTATION " << m_md5_hash.accum << ' ' << m_md5_hash.append << std::endl;*/
        }
Damien Leroux's avatar
Damien Leroux committed
571
572
573
574

        std::string get_path() const
        {
            std::stringstream ss;
575
576
            ss << cache_directory() << '/' << m_name;
            ensure_directory_exists(ss.str());
577
            /*ss << cache_directory() << '/' << m_name << '_' << m_md5_hash.accum << '_' << typeid(Ret).name();*/
578
            ss << '/' << m_md5_hash.accum;
Damien Leroux's avatar
Damien Leroux committed
579
580
581
            return ss.str();
        }

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
        bool __load(const std::string& path, Ret& data)
        {
            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 */
                    /*MSG_INFO('(' << m_name << ") Found data in cache");*/
                ci & data;
            /*     return value read from file */
                return true;
597
598
            } else {
                MSG_WARNING("Collision in cache! " << path);
599
600
601
602
            }
            return false;
        }

Damien Leroux's avatar
Damien Leroux committed
603
604
605
606
607
        Ret operator () (Args... x)
        {
            Ret data;
            std::string path = get_path();
            /* if cache file found */
608
            if (check_file(path, false, true, false)) {
Damien Leroux's avatar
Damien Leroux committed
609
610
611
612
613
614
615
616
617
                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 */
618
                    /*MSG_INFO('(' << m_name << ") Found data in cache");*/
Damien Leroux's avatar
Damien Leroux committed
619
620
621
622
623
                    ci & data;
            /*     return value read from file */
                    return data;
                }
            /*   CACHE INVALID */
624
                /*MSG_INFO('(' << m_name << ") Cache is invalid. Computing data.");*/
Damien Leroux's avatar
Damien Leroux committed
625
626
627
            } else {
            /* else */
            /*   COMPUTE AND SAVE */
628
                /*MSG_INFO('(' << m_name << ") Computing data.");*/
Damien Leroux's avatar
Damien Leroux committed
629
630
631
632
633
            }
            /* compute value = m_func(x...) */
            data = m_func(x...);
            /* write m_md5_hash.append to file */
            std::ofstream ofs(path);
634
635
636
637
638
639
640
641
642
643
644
645
646
647
            {
                cache_output co(ofs);
                co & m_md5_hash.append;
                /* write value to file */
                co & data;
            }
            if (0) { /* check stored data */
                Ret check;
                if (!__load(path, check)) {
                    MSG_ERROR("Failed to load the data we just saved :(", "Call 911");
                } else if (!(check == data)) {
                    MSG_ERROR("The data we just saved is bogus :(", "Call 911");
                }
            }
Damien Leroux's avatar
Damien Leroux committed
648
649
650
651
            /* return value */
            return data;
        }

652
    /*protected:*/
Damien Leroux's avatar
Damien Leroux committed
653
654
655
656
657
658
659
660
661
662
        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;

663
        computed_value(CachingPolicy _Sync, Ret (*func) (Args...), const value<typename clean_type<Args>::type>&... args)
Damien Leroux's avatar
Damien Leroux committed
664
            : m_hash(compute_hash(args...))
665
            , m_task(make_async_computation<Ret, Args...>(_Sync, func, args...))
Damien Leroux's avatar
Damien Leroux committed
666
667
668
669
        {}

        virtual
            value_type& operator * ()
670
            override { return m_task->__get_noconst(); }
Damien Leroux's avatar
Damien Leroux committed
671
672
        virtual
            value_type* operator -> ()
673
            override { return &m_task->__get_noconst(); }
Damien Leroux's avatar
Damien Leroux committed
674
675
        virtual
            const value_type& operator * () const
676
            override { return m_task->__get_const(); }
Damien Leroux's avatar
Damien Leroux committed
677
678
        virtual
            const value_type* operator -> () const
679
            override { return &m_task->__get_const(); }
Damien Leroux's avatar
Damien Leroux committed
680
681
682
683
684
685
686
687

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

688
    /*protected:*/
Damien Leroux's avatar
Damien Leroux committed
689
        size_t m_hash;
690
        std::shared_ptr<async_computation<Ret(Args...)>> m_task;
Damien Leroux's avatar
Damien Leroux committed
691
692
693
694
695
696
697
    };

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;

698
        cached_computed_value(CachingPolicy _Sync, Ret (*func) (Args...), const value<typename clean_type<Args>::type>&... args)
699
            : m_comp(get_func_name(func), func, args...)
Damien Leroux's avatar
Damien Leroux committed
700
            , m_comp_proxy([this](Args... x) { return m_comp(x...); })
701
            , m_task(make_async_computation<Ret, Args...>(_Sync, func, m_comp_proxy, args...))
Damien Leroux's avatar
Damien Leroux committed
702
        {}
703
704
            /*m_hash = m_comp.m_md5_hash.md5.context;*/
        /*}*/
Damien Leroux's avatar
Damien Leroux committed
705
706
707

        virtual
            value_type& operator * ()
708
            override { return m_task->__get_noconst(); }
Damien Leroux's avatar
Damien Leroux committed
709
710
        virtual
            value_type* operator -> ()
711
            override { return &m_task->__get_noconst(); }
Damien Leroux's avatar
Damien Leroux committed
712
713
        virtual
            const value_type& operator * () const
714
            override { return m_task->__get_const(); }
Damien Leroux's avatar
Damien Leroux committed
715
716
        virtual
            const value_type* operator -> () const
717
            override { return &m_task->__get_const(); }
Damien Leroux's avatar
Damien Leroux committed
718
719

        virtual
720
721
722
            size_t hash() const override
            /*override { return m_hash; }*/
            {
723
                (void)m_task->__get_const();
724
725
                return m_comp.m_md5_hash.md5.context;
            }
Damien Leroux's avatar
Damien Leroux committed
726
        virtual
727
728
            md5_digest& md5(md5_digest& md) const override
            {
729
                (void)m_task->__get_const();
730
731
732
                return md.blend(m_comp.m_md5_hash.md5.context);
            }
            /*override { return md; }*/
Damien Leroux's avatar
Damien Leroux committed
733

734
    /*protected:*/
Damien Leroux's avatar
Damien Leroux committed
735
736
        cached_computation<Ret(Args...)> m_comp;
        std::function<Ret(Args...)> m_comp_proxy;
737
        std::shared_ptr<async_computation<Ret(Args...)>> m_task;
738
        /*size_t m_hash;*/
Damien Leroux's avatar
Damien Leroux committed
739
740
741
742
743
744
745
746
747
748
749
750
751
    };


/* 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 {
Damien Leroux's avatar
Damien Leroux committed
752
            T m_data;
Damien Leroux's avatar
Damien Leroux committed
753
754
755
            T m_step;
            T m_max;
            iterator(T value, T max, T step)
Damien Leroux's avatar
Damien Leroux committed
756
                : m_data(value), m_step(step), m_max(max)
Damien Leroux's avatar
Damien Leroux committed
757
758
759
            {}
            iterator& operator ++ ()
            {
Damien Leroux's avatar
Damien Leroux committed
760
761
762
                m_data += m_step;
                if (m_data > m_max) {
                    m_data = m_max;
Damien Leroux's avatar
Damien Leroux committed
763
764
765
766
767
                }
                return *this;
            }
            bool operator == (const iterator& i) const
            {
Damien Leroux's avatar
Damien Leroux committed
768
                return m_data == i.m_data;
Damien Leroux's avatar
Damien Leroux committed
769
770
771
            }
            bool operator != (const iterator& i) const
            {
Damien Leroux's avatar
Damien Leroux committed
772
                return m_data != i.m_data;
Damien Leroux's avatar
Damien Leroux committed
773
            }
Damien Leroux's avatar
Damien Leroux committed
774
            value<T> operator * () const { return {m_data}; }
Damien Leroux's avatar
Damien Leroux committed
775
776
777
778
779
780
        };
        iterator begin() const { return {m_min, m_max, m_step}; }
        iterator end() const { return {m_max, m_max, 0}; }
    };


781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
template <typename _Coll>
    struct as_collection {
        typedef typename _Coll::value_type T;
        typedef typename _Coll::const_iterator ci_type;

        ci_type m_begin, m_end;

        as_collection(const _Coll& c)
            : m_begin(c.begin()), m_end(c.end())
        {}

        struct iterator {
            ci_type ci;
            iterator(const ci_type& it)
                : ci(it)
            {}
            iterator& operator ++ ()
            {
                ++ci;
                return *this;
            }
            bool operator == (const iterator& i) const
            {
                return ci == i.ci;
            }
            bool operator != (const iterator& i) const
            {
                return ci != i.ci;
            }
            value<T> operator * () const { return value<T>{*ci}; }
        };

        iterator begin() const { return {m_begin}; }
        iterator end() const { return {m_end}; }
    };

template <typename _Coll>
as_collection<_Coll> values_of(const _Coll& c) { return {c}; }

Damien Leroux's avatar
Damien Leroux committed
820
821
822
823
824
825
template <typename X>
value<X> as_value(const X& x) { return {x}; }

/*template <typename X>*/
/*value<X> as_value(X&& x) { return {x}; }*/

Damien Leroux's avatar
Damien Leroux committed
826
827
828
829
830
831
832
833
834
835
836
#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


837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
#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
852
853
854


template <typename Ret, typename... Args>
855
856
857
struct with_disk_cache_traits {
	typedef cached_computed_value<Ret(Args...)> type;
};
Damien Leroux's avatar
Damien Leroux committed
858
859

template <typename Ret, typename... Args>
860
861
862
struct without_disk_cache_traits {
	typedef computed_value<Ret(Args...)> type;
};
Damien Leroux's avatar
Damien Leroux committed
863

864
865
template <int _Policy, typename Ret, typename... Args>
struct disk_cache_traits;
Damien Leroux's avatar
Damien Leroux committed
866

867
template <typename Ret, typename... Args>
868
struct disk_cache_traits<Oneshot, Ret, Args...> : without_disk_cache_traits<Ret, Args...> {};
869
870

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

873
874
875
876
877
878
879
template <typename Ret, typename... Args>
struct with_mem_cache_traits {
	typedef value<Ret>& return_type;

	template <typename _Maker>
		static
		return_type
880
		create(CachingPolicy _Sync, Ret (&f) (Args...), const clean_value_type<Args>&... x)
881
		{
Damien Leroux's avatar
Damien Leroux committed
882
883
            static std::mutex _;
            std::lock_guard<std::mutex> lock_guard(_);
884

885
            /*value<Ret>* ret_in_progress = __get_in_progress_registry<Ret, Args...>().find(&f, x...);*/
886

887
888
889
            /*if (ret_in_progress) {*/
                /*return *ret_in_progress;*/
            /*}*/
890

891
892
893
			/*MSG_DEBUG("new value with mem cache");*/
			return_type ret = __get_registry<Ret, Args...>().get(&f, x...);
			if (!ret.valid()) {
894
				ret = new _Maker(_Sync, f, x...);
895
896
897
898
899
900
901
902
903
904
905
906
			}
			return ret;
		}
};

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

	template <typename _Maker>
		static
		return_type
907
		create(CachingPolicy _Sync, Ret (&f) (Args...), const clean_value_type<Args>&... x)
908
		{
Damien Leroux's avatar
Damien Leroux committed
909
910
            static std::mutex _;
            std::lock_guard<std::mutex> lock_guard(_);
911
            /*value<Ret>* ret_in_progress = __get_in_progress_registry<Ret, Args...>().find(&f, x...);*/
912

913
914
915
            /*if (ret_in_progress) {*/
                /*return *ret_in_progress;*/
            /*}*/
916

917
			/*MSG_DEBUG("new value without mem cache");*/
918
			return_type ret = new _Maker(_Sync, f, x...);
919
920
921
922
923
924
925
926
			return ret;
		}
};

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

template <typename Ret, typename... Args>
927
struct mem_cache_traits<Oneshot, Ret, Args...> : without_mem_cache_traits<Ret, Args...> {};
928
929

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

932
933
template <CachingPolicy _Policy = Oneshot, typename Ret, typename... Args>
typename mem_cache_traits<_Policy & Mem, Ret, Args...>::return_type
934
935
make_value(Ret (&f) (Args...), const clean_value_type<Args>&... x)
{
936
937
938
	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...);
939
}
Damien Leroux's avatar
Damien Leroux committed
940
941
942

template <typename T> struct collection : std::vector<value<T>> {
    using std::vector<value<T>>::vector;
943
944
945
946
947
948
949
950
951
    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
952
953
};

954
955
template <typename... X> struct tuple;

956
template <CachingPolicy C, typename F, typename R, typename P> struct make_coll_impl;
Damien Leroux's avatar
Damien Leroux committed
957
958
959
960
961
962
963
964
965
966

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;
967
template <> struct type_lists_must_be_identical<tuple<>, tuple<>> {};
Damien Leroux's avatar
Damien Leroux committed
968
969

template <typename A0, typename... A, typename B0, typename... B>
970
971
    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
972
973
974
        static_assert(types_must_be_identical<A0, B0>::value, "INVALID PARAMETER TYPE.");
    };

975
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename... ErrArgs>
976
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<>, tuple<ErrArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
977
978
979
980
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      ErrArgs... errargs)
    {
981
        type_lists_must_be_identical<tuple<FuncArgs...>, tuple<typename ErrArgs::value_type...>>();
982
        coll.push_back(make_value<_Policy>(f, errargs...));
Damien Leroux's avatar
Damien Leroux committed
983
984
985
    }
};

986
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs>
987
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<>, tuple<clean_value_type<FuncArgs>...>> {
Damien Leroux's avatar
Damien Leroux committed
988
989
990
991
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),
                      const value<typename clean_type<FuncArgs>::type>&... pargs)
    {
992
        coll.push_back(make_value<_Policy>(f, pargs...));
Damien Leroux's avatar
Damien Leroux committed
993
994
995
996
    }
};


997
template <CachingPolicy _Policy, typename Ret, typename... FuncArgs, typename VT, typename... ArgsRemaining, typename... PreviousArgs>
998
struct make_coll_impl<_Policy, Ret(FuncArgs...), tuple<value<VT>, ArgsRemaining...>, tuple<PreviousArgs...>> {
Damien Leroux's avatar
Damien Leroux committed
999
1000
    void operator () (collection<Ret>& coll,
                      Ret (&f) (FuncArgs...),