package org.glassfish.jaxb.runtime.v2.runtime.unmarshaller;

import org.apache.commons.lang3.RandomUtils;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.infra.Blackhole;

import java.io.IOException;

@State(Scope.Benchmark)
@Fork(3)
public class IsolatedBase64Data {

    private Base64Data[] base64Data;
    private char[] buf;

    @Setup
    public void setup() throws IOException {
        final var SIZE = 100_000;
        System.out.println("Creating " + SIZE + " Base64Data with length of 10000 bytes");
        base64Data = new Base64Data[SIZE];
        for (int i = 0; i < SIZE; i++) {
            base64Data[i] = new Base64Data();
            base64Data[i].set(RandomUtils.secure().randomBytes(10000), null);
            base64Data[i].length();
        }
        buf = new char[((10000 + 2) / 3) * 4];
    }

    @Benchmark
    public void base64CharAt(Blackhole blackhole) {
        for (var data : base64Data) {
            for (int i = 0; i < data.length(); i++)
                buf[i] = data.charAt(i);  // isn't this kinda slow?
            blackhole.consume(buf);
        }
    }

    @Benchmark
    public void base64WriteTo(Blackhole blackhole) {
        for (var data : base64Data) {
            data.writeTo(buf, 0);
            blackhole.consume(buf);
        }
    }

    public static void main(String[] args) throws IOException {
        var test = new IsolatedBase64Data();
        test.setup();
        for (var data : test.base64Data) {
            for (int i = 0; i < data.length(); i++)
                test.buf[i] = data.charAt(i);  // isn't this kinda slow?
        }
    }

}


/*

for 1000 byte chunks
Benchmark                          Mode  Cnt   Score   Error  Units
IsolatedBase64Data.base64CharAt   thrpt   15   5,714 ± 0,312  ops/s
IsolatedBase64Data.base64WriteTo  thrpt   15  13,032 ± 0,223  ops/s

 */