You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB

2 years ago
#include "mdatetime.h"
#include <memory>
#include <vector>
#if !defined(M__TINDEXES)
#define M__TINDEXES
using michlib::MDateTime;
template<class T> std::vector<size_t> GetTIndexes(const T& adapter, const MDateTime& b, const MDateTime& e)
{
std::vector<size_t> out;
auto nt = adapter.NTimes();
const MDateTime& beg = (b < e) ? b : e;
const MDateTime& end = (b > e) ? b : e;
if(beg > adapter.Time(nt - 1) || end < adapter.Time(0)) return out;
size_t ib = 0, ie = nt - 1;
for(size_t i = 0; i < nt; i++)
if(adapter.Time(i) >= beg)
{
ib = i;
break;
}
for(size_t i = nt; i != 0; i--)
if(adapter.Time(i - 1) <= end)
{
ie = i - 1;
break;
}
out.resize(ie - ib + 1);
for(size_t i = 0; i < ie - ib + 1; i++) out[i] = i + ib;
return out;
}
template<class T> std::vector<size_t> GetTIndexes(const T& adapter, const MString& regex)
{
std::vector<size_t> out;
std::unique_ptr<regex_t> regbuf(new regex_t);
if(0 != regcomp(regbuf.get(), regex.Buf(), REG_EXTENDED | REG_NOSUB)) return out;
for(size_t i = 0; i < adapter.NTimes(); i++)
{
MString date = adapter.Time(i).ToString();
if(0 != regexec(regbuf.get(), date.Buf(), 0, 0, 0)) continue;
out.push_back(i);
}
return out;
}
template<class T> size_t GetTIndex(const T& adapter, const MDateTime& t)
{
size_t nt = adapter.NTimes();
if(t <= adapter.Time(0)) return 0;
if(t >= adapter.Time(nt - 1)) return nt - 1;
for(size_t i = 0; i < nt - 1; i++)
if(t >= adapter.Time(i) && t <= adapter.Time(i + 1)) return (t - adapter.Time(i) <= adapter.Time(i + 1) - t) ? i : (i + 1);
return 0;
}
#endif