2 integration: custom serializer which naïvly decides to write strings/clobs/blobs
10 class AutoUtf8 extends ion\Serializer\Serializer {
11 public function serialize(mixed $data, \ion\Writer|array|null $writer = null): mixed {
12 return parent::serialize($data, new class extends \ion\Writer\Buffer\Writer {
13 private function iterate(string $s) : Generator {
14 for ($i = 0; $i < grapheme_strlen($s); ++$i) {
15 yield grapheme_substr($s, $i, 1);
18 private function classify(string $c) : bool {
21 } elseif ($c < "\040") return match ($c) {
22 "\n", "\r", "\t" => false,
27 public function writeString(string $value) : void {
29 foreach ($this->iterate($value) as $c) {
33 ++$dist[$this->classify($c)];
35 if ($dist[0] <= $dist[1]) {
37 parent::writeBLob($value);
39 parent::writeCLob($value);
41 parent::writeString($value);
48 $data = ["abc", "äöü", "\nabc\n", "foo\0bar", hex2bin("1f8b08003d96676200034bcacc4b2caae40200f5127b4207000000")];
49 echo ion\serialize($data), "\n";
50 echo ion\serialize($data, new AutoUtf8), "\n";
55 ["abc","äöü","\nabc\n","foo\0bar","\x1F%s\x12{B\a\0\0\0"]
56 ["abc","äöü","\nabc\n",{{"foo\0bar"}},{{H4sIAD2WZ2IAA0vKzEssquQCAPUSe0IHAAAA}}]