Advertisement
tinyevil

Untitled

Oct 31st, 2018
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. struct Iterator{
  2.     Boolean(*next) (Iterator* iterator, Any* key, Any* value);
  3.  
  4.     alignas(std::max_align_t)
  5.     uint8_t payload[4 * 8];
  6. };
  7.  
  8. struct DynamicIterator{
  9.     Dynamic* object;
  10.     Dynamic::map_t::iterator it;
  11. };
  12.  
  13. Boolean Dynamic::iterate(Dynamic* dyn, Iterator* iterator){
  14.     DynamicIterator* iter = (DynamicIterator*)iterator->payload;
  15.     new(&iter->it)Dynamic::map_t::iterator(std::move(dyn->map.begin()));
  16.     iter->object = dyn;
  17.     iterator->next = [](Iterator* iterator, Any* key, Any* value) -> Boolean{
  18.         DynamicIterator* iter = (DynamicIterator*)iterator->payload;
  19.         if ( iter->it == iter->object->map.end() ){
  20.             std::destroy_at(&iter->it); // if it was the last iteration, destroy it
  21.             return false;
  22.         }
  23.         *key = iter->it->first;
  24.         *value = iter->it->second;
  25.         iter->it++;
  26.         return true;
  27.     };
  28.     return true;
  29. }
  30.  
  31.  
  32. // somewhere in the user code...
  33.  
  34. Any object = ...; // <- iterable object
  35. Iterator iter;
  36. Any key;
  37. Any value;
  38.  
  39. any_iter(object, &iter); // any iterator does dynamic dispatch and eventually invokes Dynamic::iterate
  40.  
  41. while ( iter.next(&iter, &key, &value) ){
  42.     // do something
  43.     if ( something ){
  44.         return; // this leaves without destroying std::map::iterator inside Iterator
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement