File: CharPooledMemory.hpp

package info (click to toggle)
bedops 2.4.41%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 21,148 kB
  • sloc: ansic: 28,562; cpp: 15,359; sh: 2,704; makefile: 2,687; xml: 1,669; python: 1,582; csh: 823; perl: 365; java: 172
file content (521 lines) | stat: -rw-r--r-- 14,879 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
74
75
76
77
78
79
80
81
82
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
160
161
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
315
316
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
  Author: Shane Neph
  Date:   Thu Nov 24 20:16:29 PST 2016
*/
//
//    BEDOPS
//    Copyright (C) 2011-2016 Shane Neph, Scott Kuehn and Alex Reynolds
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along
//    with this program; if not, write to the Free Software Foundation, Inc.,
//    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#ifndef UTILS_SIMPLE_CHARARRAY_MEM
#define UTILS_SIMPLE_CHARARRAY_MEM

#include <cstring>
#include <exception>
#include <functional>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <utility>


#include "utility/BitMonitor.hpp"

namespace Ext {

  template <std::size_t Sz>
  struct PooledCharMemory2 {

    PooledCharMemory2() : _curr(new MemChunk()), _cache(nullptr)
      {
        _blocks.insert(_curr);
        _blockstarts.insert(_curr->_data);
        _r.insert(std::make_pair(_curr->_data, _curr));
      }

    inline std::size_t
    nblocks() const { return _blocks.size(); }

    inline char*
    construct(char const* val)
      {
        auto p = _curr->add(val);
        if ( p )
          return p;

        /* current memory block is full */
        if ( _cache ) {
          _cache->clear();
          _curr = _cache;
          _cache = nullptr;
          _blocks.insert(_curr);
          _blockstarts.insert(_curr->_data);
          _r.insert(std::make_pair(_curr->_data, _curr));
        } else {
          for ( auto& i : _blocks ) {
            /* ensure no current block can accept val
               before adding another MemChunk
            */
            if ( i != _curr ) {
              auto q = i->add(val);
              if ( q ) {
                _curr = i;
                return q;
              }
            }
          } // for
          if ( std::strlen(val) > Sz )
            throw std::logic_error("Cannot store a string that large in PooledCharMemory2<Sz>");
          _curr = new MemChunk();
          _blocks.insert(_curr);
          _blockstarts.insert(_curr->_data);
          _r.insert(std::make_pair(_curr->_data, _curr));
        }
        return _curr->add(val);
      }

    inline void
    release(char* b)
      {
        if ( 1 == _blockstarts.size() )
          _curr->remove(b);
        else { // possible Chunk removal
          auto iter = _blockstarts.begin();
          MemChunk* m;
          if ( _blockstarts.size() < 10 ) {
            auto miter = _r.begin();
            while ( *iter > b ) { ++iter; ++miter; }
            m = miter->second;
          } else {
            iter = _blockstarts.lower_bound(b);
            m = _r[*iter];
          }
          m->remove(b);
          if ( m->empty() ) {
            _blocks.erase(m);
            _blockstarts.erase(iter);
            _r.erase(*iter);
            if ( !_cache )
              _cache = m;
            else
              delete m;
            if ( m == _curr )
              _curr = *(_blocks.begin()); // important if we drop back to 1 block
          }
        }
      }

    ~PooledCharMemory2()
      {
        for ( auto b : _blocks )
          delete b;
        if ( _cache )
          delete _cache;
      }

  private:
    template <std::size_t nelements>
    struct CharChunk {
      static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();

      CharChunk() : _cc(0), _cntr(0), _data{} /*, _tracker(nelements), _dirty(nelements)*/
        {
          _data[nelements] = '\0';
          /* leave _open empty until we've exhausted first pass of nelements */
        }

      inline bool
      empty() const
        {
          return _cntr == 0;
        }

      inline char*
      add(char const* c)
        {
          /* not protecting against c == nullptr in private, nested class */
          if ( _cc == nelements ) {
            auto a = find_open(c);
            if ( a )
              ++_cntr;
            return a;
          }

          std::size_t i = 0, start = _cc;
          bool ok = false;
          while ( start < nelements ) {
            _data[start++] = c[i];
            if ( c[i++] == '\0' ) {
              ok = true;
              break;
            }
          } // while

          if ( start == nelements && c[i] == '\0' ) {
            _data[start] = '\0'; // _data has nelements+1
            ok = true;
          }

          if ( ok ) {
            std::swap(start, _cc);
            ++_cntr;
            _tracker.set(start);
            return _data+start;
          }
          auto a = find_open(c);
          if ( a )
            ++_cntr;
          return a;
         }

      inline void
      remove(char const* c)
        {
          _dirty.set(c - _data);
          _tracker.unset(c - _data);
          --_cntr;
        }

      inline void
      clear()
        {
          _cntr = 0;
          _cc = 0;
          _data[nelements] = '\0';
          _tracker.unset_all();
          _dirty.unset_all();
          _open.clear();
        }

    private:
      char*
      find_open(char const* c)
        {
          std::size_t need = std::strlen(c);

          auto nxt = _open.lower_bound(need);
          if ( nxt != _open.end() ) {
            std::strcpy(_data+nxt->second, c);
            std::size_t newlength = (nxt->first-need);
            if ( newlength > 1 ) { // if == 1, can only hold '\0'
              _open.insert(std::make_pair(newlength-1, nxt->second+need+1));
              _dirty.set(nxt->second+need+1);
            }
            _dirty.unset(nxt->second);
            _tracker.set(nxt->second);
            _open.erase(nxt);
            return _data+nxt->second;
          }

          std::size_t f = _dirty.find_first_set(), f2 = 0, g;
          while ( f != _dirty.npos ) {
            g = _tracker.next_set(f);
            if ( g == _tracker.npos )
              g = nelements;

            f2 = f;
            while ( (f2 = _dirty.next_set(f2)) < g ) {
              if ( f2 == _dirty.npos )
                break;
              _dirty.unset(f2);
            } // while

            if ( g-f > need ) {
              std::strcpy(_data+f, c);
              _dirty.unset(f);
              _dirty.set(f+need);
              _tracker.set(f);
              return _data+f;
            }

            if ( _open.size()<MAXLOOKUP && (g-f)>1 )
              _open.insert(std::make_pair(g-f-1, f));
            else if ( _open.size() == MAXLOOKUP && (g-f)>(_open.begin()->first) ) {
              _open.insert(std::make_pair(g-f-1, f));
              _open.erase(_open.begin());
            }

            f = f2;
          } // while
          return nullptr;
        }

      friend struct PooledCharMemory2<nelements>;

      static constexpr std::size_t MAXLOOKUP = 100;

      std::size_t _cc;
      std::size_t _cntr;
      char _data[nelements+1];
      BSet<nelements> _tracker, _dirty;
      std::multimap<std::size_t, std::size_t> _open; // size, position
    };

    typedef CharChunk<Sz> MemChunk;

    MemChunk* _curr;
    MemChunk* _cache;
    // Important to remember that _blocks, _blockstarts, _r all have the same #elements
    std::set<MemChunk*, std::greater<MemChunk*>> _blocks;
    std::set<char*, std::greater<char*>> _blockstarts;
    std::map<char*, MemChunk*, std::greater<char*>> _r;
  };

  /*********************************************************
  *********************************************************/
  template <std::size_t Sz>
  struct PooledCharMemory {

    PooledCharMemory() : _curr(new MemChunk()), _cache(nullptr)
      {
        _blocks.insert(_curr);
        _blockstarts.insert(_curr->_data);
        _r.insert(std::make_pair(_curr->_data, _curr));
      }

    inline std::size_t
    nblocks() const { return _blocks.size(); }

    inline char*
    construct(char const* val)
      {
        auto p = _curr->add(val);
        if ( p )
          return p;

        /* current memory block is full */
        if ( _cache ) {
          _cache->clear();
          _curr = _cache;
          _cache = nullptr;
          _blocks.insert(_curr);
          _blockstarts.insert(_curr->_data);
          _r.insert(std::make_pair(_curr->_data, _curr));
        } else {
          for ( auto& i : _blocks ) {
            /* ensure no current block can accept val
               before adding another MemChunk
            */
            if ( i != _curr ) {
              auto q = i->add(val);
              if ( q ) {
                _curr = i;
                return q;
              }
            }
          } // for
          if ( std::strlen(val) > Sz )
            throw std::logic_error("Cannot store a string that large in PooledCharMemory<Sz>");
          _curr = new MemChunk();
          _blocks.insert(_curr);
          _blockstarts.insert(_curr->_data);
          _r.insert(std::make_pair(_curr->_data, _curr));
        }
        auto r = _curr->add(val);
        return r;
      }

    inline void
    release(char* b)
      {
        if ( 1 == _blockstarts.size() )
          _curr->remove(b);
        else { // possible Chunk removal
          auto iter = _blockstarts.begin();
          MemChunk* m;
          if ( _blockstarts.size() < 10 ) {
            auto miter = _r.begin();
            while ( *iter > b ) { ++iter; ++miter; }
            m = miter->second;
          } else {
            iter = _blockstarts.lower_bound(b);
            m = _r[*iter];
          }
          m->remove(b);
          if ( m->empty() ) {
            _blocks.erase(m);
            _blockstarts.erase(iter);
            _r.erase(*iter);
            if ( !_cache )
              _cache = m;
            else
              delete m;
            if ( m == _curr )
              _curr = *(_blocks.begin()); // important if we drop back to 1 block
          }
        }
      }

    ~PooledCharMemory()
      {
        for ( auto b : _blocks )
          delete b;
        if ( _cache )
          delete _cache;
      }

  private:
    template <std::size_t nelements>
    struct CharChunk {
      static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();

      CharChunk() : _cc(0), _cntr(0), _data{}
        {
          _data[nelements] = '\0';
          /* leave _open empty until we've exhausted first pass of nelements */
        }

      inline bool
      empty() const
        {
          return _cntr == 0;
        }

      inline char*
      add(char const* c)
        {
          /* not protecting against c == nullptr in private, nested class */
          if ( _cc == nelements ) {
            auto a = find_open(c);
            if ( a ) {
              ++_cntr;
              _tracker.set(a - _data);
            }
            return a;
          }

          std::size_t i = 0, start = _cc;
          bool ok = false;
          while ( start < nelements ) {
            _data[start++] = c[i];
            if ( c[i++] == '\0' ) {
              ok = true;
              break;
            }
          } // while

          if ( start == nelements && c[i] == '\0' ) {
            _data[start] = '\0'; // _data has nelements+1
            ok = true;
          }

          if ( ok ) {
            std::swap(start, _cc);
            ++_cntr;
            _tracker.set(start);
            return _data+start;
          }

          auto a = find_open(c);
          if ( a ) {
            ++_cntr;
            _tracker.set(a - _data);
          }
          return a;
        }

      inline void
      remove(char const* c)
        {
          _dirty.push_back(c - _data);
          _tracker.unset(c - _data);
          --_cntr;
        }

      inline void
      clear()
        {
          _cntr = 0;
          _cc = 0;
          _open.clear(); // leave empty until we've exhausted first pass of nelements
          _dirty.clear();
          _tracker.unset_all();
          _data[nelements] = '\0';
        }

    private:
      inline char*
      find_open(char const* c)
        {
          std::size_t sz = std::strlen(c);
          auto nxt = _open.lower_bound(sz);
          if ( nxt != _open.end() ) {
            std::strcpy(_data+nxt->second, c);
            std::size_t newlength = (nxt->first-sz);
            if ( newlength > 1 ) // if == 1, can only hold '\0'
              _open.insert(std::make_pair(newlength-1, nxt->second+sz+1));
            _tracker.set(nxt->second);
            _open.erase(nxt);
            return _data+nxt->second;
          }
          return clean(c, sz);
        }

      char*
      clean(char const* c, std::size_t need)
        {
          // potentially very slow; try to find first location that fits c
          for ( auto iter = _dirty.begin(); iter != _dirty.end(); iter = _dirty.erase(iter) ) {
            std::size_t pos = *iter;
            std::size_t lng = _tracker.next_set(pos, nelements);
            if ( lng != _tracker.npos )
              lng -= (pos+1); // +1 for '\0'; lng is at least 1 bigger than pos
            else
              lng = nelements + 1 - pos; // +1 b/c _data has nelements+1 elements with last == '\0'

            if ( lng >= need ) {
              std::strcpy(_data+pos, c);
              _tracker.set(pos);
              if ( lng-need > 1 ) // if == 1, can only hold '\0'
                _open.insert(std::make_pair(lng-need-1, pos+need+1));
              _dirty.erase(iter);
              return _data+pos;
            }
            else
              _open.insert(std::make_pair(lng, pos));
          } // for
          _dirty.clear();
          return nullptr;
        }

      friend struct PooledCharMemory<nelements>;

      static constexpr std::size_t BaseSize = std::numeric_limits<unsigned char>::digits;
      static constexpr std::size_t NBits = Pow<BaseSize, IntLogN<BaseSize, nelements>::value>::value;

      std::size_t _cc;
      std::size_t _cntr;
      char _data[nelements+1];
      BitMonitor2<BaseSize, NBits> _tracker;
      std::multimap<std::size_t, std::size_t> _open; // size, position
      std::list<std::size_t> _dirty; // position
    };

    typedef CharChunk<Sz> MemChunk;

    MemChunk* _curr;
    MemChunk* _cache;
    // Important to remember that _blocks, _blockstarts, _r all have the same #elements
    std::set<MemChunk*, std::greater<MemChunk*>> _blocks;
    std::set<char*, std::greater<char*>> _blockstarts;
    std::map<char*, MemChunk*, std::greater<char*>> _r;
  };

} // namespace Ext

#endif // UTILS_SIMPLE_CHARARRAY_MEM