
#include "repl.hh"

namespace afilter {

  template <typename T>
  void utf8_unichar<T>::fill(char c, Itr * i, Buffer * out) {
    while ((c & 0xC0) == 0x80) c = i->next();
    if ((c & 0x80) == 0x00) { // 1-byte wide
      *out += c;
    } else if ((c & 0xE0) == 0xC0) { // 2-byte wide
      unichar u = c & 0x1F; u <<= 6;
      u |= i->next() & 0x3F;
      *out += u;
    } else if ((c & 0xF0) == 0xE0) { // 3-byte wide
      unichar u = c & 0x0F; u <<= 6;
      u |= i->next() & 0x3F; u <<= 6;
      u |= i->next() & 0x3F;
      *out += u;
    } else if ((c & 0xF8) == 0xF0) { // 4-byte wide
      unichar u = c & 0x0E; u <<= 6;
      u |= i->next() & 0x3F; u <<= 6;
      u |= i->next() & 0x3F; u <<= 6;
      u |= i->next() & 0x3F;
      *out += u;
    }
  }

  template <typename T>
  void unichar_utf8<T>::fill(unichar c, Itr *, Buffer * out) {
    if (c < 0x80) {
      *out += c;
    }
    else if (c < 0x800) {
      *out += (0xC0 | c>>6);
      *out += (0x80 | c & 0x3F);
    }
    else if (c < 0x10000) {
      *out += (0xE0 | c>>12);
      *out += (0x80 | c>>6 & 0x3F);
      *out += (0x80 | c & 0x3F);
    }
    else if (c < 0x200000) {
      *out += (0xF0 | c>>18);
      *out += (0x80 | c>>12 & 0x3F);
      *out += (0x80 | c>>6 & 0x3F);
      *out += (0x80 | c & 0x3F);
    }
  }

}
  
