about summary refs log blame commit diff stats
path: root/cpp/034exclusive_container
blob: 2c3a603d10c9ee6ce9af978c615790011960aef3 (plain) (tree)





















































                                                                                                                                                  
//: Exclusive containers contain exactly one of a fixed number of 'variants'
//: of different types.
//:
//: They also implicitly contain a tag describing precisely which variant is
//: currently stored in them.

:(before "End Mu Types Initialization")
//: We'll use this container as a running example, with two integer elements.
{
int tmp = Type_number["integer-or-point"] = Next_type_number++;
Type[tmp].size = 2;
Type[tmp].kind = exclusive_container;
Type[tmp].name = "integer-or-point";
//? cout << tmp << ": " << Type[tmp].elements.size() << '\n'; //? 1
vector<type_number> t1;
t1.push_back(integer);
Type[tmp].elements.push_back(t1);
//? cout << Type[tmp].elements.size() << '\n'; //? 1
vector<type_number> t2;
t2.push_back(point);
Type[tmp].elements.push_back(t2);
//? cout << Type[tmp].elements.size() << '\n'; //? 1
//? cout << "point: " << point << '\n'; //? 1
Type[tmp].element_names.push_back("i");
Type[tmp].element_names.push_back("p");
}

:(scenario "copy_exclusive_container")
# Copying exclusive containers copies all their contents and an extra location for the tag.
recipe main [
  1:integer <- copy 1:literal  # 'point' variant
  2:integer <- copy 34:literal
  3:integer <- copy 35:literal
  4:integer-or-point <- copy 1:integer-or-point
]
+mem: storing 1 in location 4
+mem: storing 34 in location 5
+mem: storing 35 in location 6

:(before "End size_of(types) Cases")
if (t.kind == exclusive_container) {
  // size of an exclusive container is the size of its largest variant
//?   cout << "--- " << types[0] << ' ' << t.size << '\n'; //? 1
//?   cout << "point: " << Type_number["point"] << " " << Type[Type_number["point"]].name << " " << Type[Type_number["point"]].size << '\n'; //? 1
//?   cout << t.name << ' ' << t.size << ' ' << t.elements.size() << '\n'; //? 1
  size_t result = 0;
  for (size_t i = 0; i < t.size; ++i) {
    size_t tmp = size_of(t.elements[i]);
//?     cout << i << ": " << t.elements[i][0] << ' ' << tmp << ' ' << result << '\n'; //? 1
    if (tmp > result) result = tmp;
  }
  // ...+1 for its tag.
  return result+1;
}