<commit_before>/*
 * Copyright 2016 Andrei Pangin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <string.h>
#include <signal.h>
#include <string>
#include <sys/time.h>

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <proto/protocol.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <unordered_set>

#include "profiler.h"
#include "vmEntry.h"

using namespace me::serce::franky;

Profiler Profiler::_instance;

static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) {
    Profiler::_instance.recordSample(ucontext);
}

MethodName::MethodName(jmethodID method) {
    jclass method_class;
    jvmtiEnv *jvmti = VM::jvmti();
    jvmti->GetMethodName(method, &_name, &_sig, NULL);
    jvmti->GetMethodDeclaringClass(method, &method_class);
    jvmti->GetClassSignature(method_class, &_class_sig, NULL);

    char *s;
    for (s = _class_sig; *s; s++) {
        if (*s == '/') *s = '.';
    }
    s[-1] = 0;
}

MethodName::~MethodName() {
    jvmtiEnv *jvmti = VM::jvmti();
    jvmti->Deallocate((unsigned char *) _name);
    jvmti->Deallocate((unsigned char *) _sig);
    jvmti->Deallocate((unsigned char *) _class_sig);
}

void CallTraceSample::assign(ASGCT_CallTrace *trace) {
    _call_count = 1;
    _num_frames = trace->num_frames;
    for (int i = 0; i < trace->num_frames; i++) {
        _frames[i] = trace->frames[i];
    }
}

uint64_t  Profiler::hashCallTrace(ASGCT_CallTrace *trace) {
    const uint64_t M = 0xc6a4a7935bd1e995LL;
    const int R = 47;

    uint64_t h = trace->num_frames * M;

    for (int i = 0; i < trace->num_frames; i++) {
        uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id;
        k *= M;
        k ^= k >> R;
        k *= M;
        h ^= k;
        h *= M;
    }

    h ^= h >> R;
    h *= M;
    h ^= h >> R;

    return h;
}

void Profiler::storeCallTrace(ASGCT_CallTrace *trace) {
    uint64_t hash = hashCallTrace(trace);
    int bucket = (int) (hash % MAX_CALLTRACES);
    int i = bucket;

    do {
        if (_hashes[i] == hash && _traces[i]._call_count > 0) {
            _traces[i]._call_count++;
            return;
        } else if (_hashes[i] == 0) {
            break;
        }
        if (++i == MAX_CALLTRACES) i = 0;
    } while (i != bucket);

    _hashes[i] = hash;
    _traces[i].assign(trace);
}

uint64_t  Profiler::hashMethod(jmethodID method) {
    const uint64_t M = 0xc6a4a7935bd1e995LL;
    const int R = 17;

    uint64_t h = (uint64_t) method;

    h ^= h >> R;
    h *= M;
    h ^= h >> R;

    return h;
}

void Profiler::storeMethod(jmethodID method) {
    uint64_t hash = hashMethod(method);
    int bucket = (int) (hash % MAX_CALLTRACES);
    int i = bucket;

    do {
        if (_methods[i]._method == method) {
            _methods[i]._call_count++;
            return;
        } else if (_methods[i]._method == NULL) {
            break;
        }
        if (++i == MAX_CALLTRACES) i = 0;
    } while (i != bucket);

    _methods[i]._call_count = 1;
    _methods[i]._method = method;
}

void Profiler::recordSample(void *ucontext) {
    _calls_total++;

    JNIEnv *jni = VM::jni();
    if (jni == NULL) {
        _calls_non_java++;
        return;
    }

    ASGCT_CallFrame frames[MAX_FRAMES];
    ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames};
    AsyncGetCallTrace(&trace, trace.num_frames, ucontext);

    if (trace.num_frames > 0) {
        storeCallTrace(&trace);
        storeMethod(frames[0].method_id);
    } else if (trace.num_frames == -2) {
        _calls_gc++;
    } else if (trace.num_frames == -9) {
        _calls_deopt++;
    } else {
        _calls_unknown++;
    }
}

void Profiler::setTimer(long sec, long usec) {
    bool enabled = sec != 0 || usec != 0;

    struct sigaction sa;
    sa.sa_handler = enabled ? NULL : SIG_IGN;
    sa.sa_sigaction = enabled ? &sigprofHandler : NULL;
    sa.sa_flags = SA_RESTART | SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGPROF, &sa, NULL);

    struct itimerval itv = {{sec, usec},
                            {sec, usec}};
    setitimer(ITIMER_PROF, &itv, NULL);
}

void Profiler::start(long interval) {
    if (_running) return;
    _running = true;

    _calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0;
    memset(_hashes, 0, sizeof(_hashes));
    memset(_traces, 0, sizeof(_traces));
    memset(_methods, 0, sizeof(_methods));

    setTimer(interval / 1000, interval * 1000);
}

void Profiler::stop() {
    if (!_running) return;
    _running = false;

    setTimer(0, 0);
}

void error(const char *msg) {
    std::string res = std::string("ERROR") + std::string(msg);
    perror(res.c_str());
    exit(0);
}

void sendResponse(int sockfd, me::serce::franky::Response &message) {
    using namespace google::protobuf;
    using namespace google::protobuf::io;

    FileOutputStream raw_output(sockfd);
    google::protobuf::io::CodedOutputStream output(&raw_output);

    // Write the size.
    const int size = message.ByteSize();
    output.WriteVarint32((uint32) size);

    uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size);
    if (buffer != NULL) {
        // Optimization:  The message fits in one buffer, so use the faster
        // direct-to-array serialization path.
        message.SerializeWithCachedSizesToArray(buffer);
    } else {
        // Slightly-slower path when the message is multiple buffers.
        message.SerializeWithCachedSizes(&output);
        if (output.HadError()) {
            error("HAD ERROR");
        }
    }
}

void Profiler::init(int port) {
    portno = (uint16_t) port;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("opening socket");
    }
    server = gethostbyname("localhost");
    if (server == NULL) {
        error("unable to connect to localhost");
    }
    struct sockaddr_in serv_addr;
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        error("connecting");
    }

    Response response;
    response.set_id(getpid());
    response.set_type(Response_ResponseType_INIT);
    sendResponse(sockfd, response);
    while (true) {
        Request request;
        readRequest(&request);

        switch (request.type()) {
            case Request_RequestType_START_PROFILING:
                start(DEFAULT_INTERVAL);
                break;
            case Request_RequestType_STOP_PROFILING:
                stop();
                writeResult();
                break;
            case Request_RequestType_DETACH:
                close(sockfd);
                return;
            default:
                continue;
        }
    }
}

void Profiler::readRequest(Request *message) {
    using namespace google::protobuf;
    using namespace google::protobuf::io;

    FileInputStream raw_input(sockfd);
    google::protobuf::io::CodedInputStream input(&raw_input);

    // Read the size.
    uint32_t size;
    if (!input.ReadVarint32(&size)) {
        error("Error reading variint32");
    }

    // Tell the stream not to read beyond that size.
    input.PushLimit(size);

    // Parse the message.
    if (!message->MergeFromCodedStream(&input)) {
        error("Error paring message 1");
    }
    if (!input.ConsumedEntireMessage()) {
        error("Error paring message 2");
    }
}

MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) {
    MethodName mn(jmethod);
    methodInfo->set_name(mn.name());
    methodInfo->set_holder(mn.holder());
    methodInfo->set_sig(mn.signature());
    return methodInfo;
}

int64_t jMethodIdToId(jmethodID &jmethod) {
    return (int64_t) jmethod;
}

void Profiler::writeResult() {
    Response response;
    ProfilingInfo *info = new ProfilingInfo();

    info->set_calls_total(_calls_total);
    info->set_calls_non_java(_calls_non_java);
    info->set_calls_gc(_calls_gc);
    info->set_calls_deopt(_calls_deopt);
    info->set_calls_unknown(_calls_unknown);

    std::unordered_set<jmethodID> methodIds;
    saveMethods(info, methodIds);
    saveCallTraces(info, methodIds);
    saveMethodIds(info, methodIds);

    response.set_id(getpid());
    response.set_type(Response_ResponseType_PROF_INFO);
    response.set_allocated_prof_info(info);
    sendResponse(sockfd, response);
}

void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
    qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator);
    int max_traces = MAX_CALLTRACES;
    for (int i = 0; i < max_traces; i++) {
        const CallTraceSample &trace = _traces[i];
        int samples = trace._call_count;
        if (samples == 0) break;

        CallTraceSampleInfo *sampleInfo = info->add_samples();
        sampleInfo->set_call_count(trace._call_count);

        for (int j = 0; j < trace._num_frames; j++) {
            const ASGCT_CallFrame *frame = &trace._frames[j];
            jmethodID jmethod = frame->method_id;
            if (jmethod != NULL) {
                CallFrame *callFrame = sampleInfo->add_frame();
                callFrame->set_bci(frame->bci);
                callFrame->set_jmethodid(jMethodIdToId(jmethod));
                methods.insert(jmethod);
            }
        }
    }
}

void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
    qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator);
    for (int i = 0; i < MAX_CALLTRACES; i++) {
        int samples = _methods[i]._call_count;
        if (samples == 0) break;

        jmethodID jmethod = _methods[i]._method;
        MethodSampleInfo *sampleInfo = info->add_methods();
        sampleInfo->set_call_count(samples);
        sampleInfo->set_jmethodid(jMethodIdToId(jmethod));
        methods.insert(jmethod);
    }
}

void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) {
    for (auto &jmethod: methodIds) {
        MethodInfo *methodInfo = info->add_methodinfos();
        fillMethodInfo(methodInfo, jmethod);
    }
}

<commit_msg>fix required field<commit_after>/*
 * Copyright 2016 Andrei Pangin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <string.h>
#include <signal.h>
#include <string>
#include <sys/time.h>

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <proto/protocol.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <unordered_set>

#include "profiler.h"
#include "vmEntry.h"

using namespace me::serce::franky;

Profiler Profiler::_instance;

static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) {
    Profiler::_instance.recordSample(ucontext);
}

MethodName::MethodName(jmethodID method) {
    jclass method_class;
    jvmtiEnv *jvmti = VM::jvmti();
    jvmti->GetMethodName(method, &_name, &_sig, NULL);
    jvmti->GetMethodDeclaringClass(method, &method_class);
    jvmti->GetClassSignature(method_class, &_class_sig, NULL);

    char *s;
    for (s = _class_sig; *s; s++) {
        if (*s == '/') *s = '.';
    }
    s[-1] = 0;
}

MethodName::~MethodName() {
    jvmtiEnv *jvmti = VM::jvmti();
    jvmti->Deallocate((unsigned char *) _name);
    jvmti->Deallocate((unsigned char *) _sig);
    jvmti->Deallocate((unsigned char *) _class_sig);
}

void CallTraceSample::assign(ASGCT_CallTrace *trace) {
    _call_count = 1;
    _num_frames = trace->num_frames;
    for (int i = 0; i < trace->num_frames; i++) {
        _frames[i] = trace->frames[i];
    }
}

uint64_t  Profiler::hashCallTrace(ASGCT_CallTrace *trace) {
    const uint64_t M = 0xc6a4a7935bd1e995LL;
    const int R = 47;

    uint64_t h = trace->num_frames * M;

    for (int i = 0; i < trace->num_frames; i++) {
        uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id;
        k *= M;
        k ^= k >> R;
        k *= M;
        h ^= k;
        h *= M;
    }

    h ^= h >> R;
    h *= M;
    h ^= h >> R;

    return h;
}

void Profiler::storeCallTrace(ASGCT_CallTrace *trace) {
    uint64_t hash = hashCallTrace(trace);
    int bucket = (int) (hash % MAX_CALLTRACES);
    int i = bucket;

    do {
        if (_hashes[i] == hash && _traces[i]._call_count > 0) {
            _traces[i]._call_count++;
            return;
        } else if (_hashes[i] == 0) {
            break;
        }
        if (++i == MAX_CALLTRACES) i = 0;
    } while (i != bucket);

    _hashes[i] = hash;
    _traces[i].assign(trace);
}

uint64_t  Profiler::hashMethod(jmethodID method) {
    const uint64_t M = 0xc6a4a7935bd1e995LL;
    const int R = 17;

    uint64_t h = (uint64_t) method;

    h ^= h >> R;
    h *= M;
    h ^= h >> R;

    return h;
}

void Profiler::storeMethod(jmethodID method) {
    uint64_t hash = hashMethod(method);
    int bucket = (int) (hash % MAX_CALLTRACES);
    int i = bucket;

    do {
        if (_methods[i]._method == method) {
            _methods[i]._call_count++;
            return;
        } else if (_methods[i]._method == NULL) {
            break;
        }
        if (++i == MAX_CALLTRACES) i = 0;
    } while (i != bucket);

    _methods[i]._call_count = 1;
    _methods[i]._method = method;
}

void Profiler::recordSample(void *ucontext) {
    _calls_total++;

    JNIEnv *jni = VM::jni();
    if (jni == NULL) {
        _calls_non_java++;
        return;
    }

    ASGCT_CallFrame frames[MAX_FRAMES];
    ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames};
    AsyncGetCallTrace(&trace, trace.num_frames, ucontext);

    if (trace.num_frames > 0) {
        storeCallTrace(&trace);
        storeMethod(frames[0].method_id);
    } else if (trace.num_frames == -2) {
        _calls_gc++;
    } else if (trace.num_frames == -9) {
        _calls_deopt++;
    } else {
        _calls_unknown++;
    }
}

void Profiler::setTimer(long sec, long usec) {
    bool enabled = sec != 0 || usec != 0;

    struct sigaction sa;
    sa.sa_handler = enabled ? NULL : SIG_IGN;
    sa.sa_sigaction = enabled ? &sigprofHandler : NULL;
    sa.sa_flags = SA_RESTART | SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGPROF, &sa, NULL);

    struct itimerval itv = {{sec, usec},
                            {sec, usec}};
    setitimer(ITIMER_PROF, &itv, NULL);
}

void Profiler::start(long interval) {
    if (_running) return;
    _running = true;

    _calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0;
    memset(_hashes, 0, sizeof(_hashes));
    memset(_traces, 0, sizeof(_traces));
    memset(_methods, 0, sizeof(_methods));

    setTimer(interval / 1000, interval * 1000);
}

void Profiler::stop() {
    if (!_running) return;
    _running = false;

    setTimer(0, 0);
}

void error(const char *msg) {
    std::string res = std::string("ERROR") + std::string(msg);
    perror(res.c_str());
    exit(0);
}

void sendResponse(int sockfd, me::serce::franky::Response &message) {
    using namespace google::protobuf;
    using namespace google::protobuf::io;

    FileOutputStream raw_output(sockfd);
    google::protobuf::io::CodedOutputStream output(&raw_output);

    // Write the size.
    const int size = message.ByteSize();
    output.WriteVarint32((uint32) size);

    uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size);
    if (buffer != NULL) {
        // Optimization:  The message fits in one buffer, so use the faster
        // direct-to-array serialization path.
        message.SerializeWithCachedSizesToArray(buffer);
    } else {
        // Slightly-slower path when the message is multiple buffers.
        message.SerializeWithCachedSizes(&output);
        if (output.HadError()) {
            error("HAD ERROR");
        }
    }
}

void Profiler::init(int port) {
    portno = (uint16_t) port;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error("opening socket");
    }
    server = gethostbyname("localhost");
    if (server == NULL) {
        error("unable to connect to localhost");
    }
    struct sockaddr_in serv_addr;
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        error("connecting");
    }

    Response response;
    response.set_id(getpid());
    response.set_type(Response_ResponseType_INIT);
    sendResponse(sockfd, response);
    while (true) {
        Request request;
        readRequest(&request);

        switch (request.type()) {
            case Request_RequestType_START_PROFILING:
                start(DEFAULT_INTERVAL);
                break;
            case Request_RequestType_STOP_PROFILING:
                stop();
                writeResult();
                break;
            case Request_RequestType_DETACH:
                close(sockfd);
                return;
            default:
                continue;
        }
    }
}

void Profiler::readRequest(Request *message) {
    using namespace google::protobuf;
    using namespace google::protobuf::io;

    FileInputStream raw_input(sockfd);
    google::protobuf::io::CodedInputStream input(&raw_input);

    // Read the size.
    uint32_t size;
    if (!input.ReadVarint32(&size)) {
        error("Error reading variint32");
    }

    // Tell the stream not to read beyond that size.
    input.PushLimit(size);

    // Parse the message.
    if (!message->MergeFromCodedStream(&input)) {
        error("Error paring message 1");
    }
    if (!input.ConsumedEntireMessage()) {
        error("Error paring message 2");
    }
}

int64_t jMethodIdToId(const jmethodID &jmethod) {
    return (int64_t) jmethod;
}

MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) {
    MethodName mn(jmethod);
    methodInfo->set_jmethodid(jMethodIdToId(jmethod));
    methodInfo->set_name(mn.name());
    methodInfo->set_holder(mn.holder());
    methodInfo->set_sig(mn.signature());
    return methodInfo;
}

void Profiler::writeResult() {
    Response response;
    ProfilingInfo *info = new ProfilingInfo();

    info->set_calls_total(_calls_total);
    info->set_calls_non_java(_calls_non_java);
    info->set_calls_gc(_calls_gc);
    info->set_calls_deopt(_calls_deopt);
    info->set_calls_unknown(_calls_unknown);

    std::unordered_set<jmethodID> methodIds;
    saveMethods(info, methodIds);
    saveCallTraces(info, methodIds);
    saveMethodIds(info, methodIds);

    response.set_id(getpid());
    response.set_type(Response_ResponseType_PROF_INFO);
    response.set_allocated_prof_info(info);
    sendResponse(sockfd, response);
}

void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
    qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator);
    int max_traces = MAX_CALLTRACES;
    for (int i = 0; i < max_traces; i++) {
        const CallTraceSample &trace = _traces[i];
        int samples = trace._call_count;
        if (samples == 0) break;

        CallTraceSampleInfo *sampleInfo = info->add_samples();
        sampleInfo->set_call_count(trace._call_count);

        for (int j = 0; j < trace._num_frames; j++) {
            const ASGCT_CallFrame *frame = &trace._frames[j];
            jmethodID jmethod = frame->method_id;
            if (jmethod != NULL) {
                CallFrame *callFrame = sampleInfo->add_frame();
                callFrame->set_bci(frame->bci);
                callFrame->set_jmethodid(jMethodIdToId(jmethod));
                methods.insert(jmethod);
            }
        }
    }
}

void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
    qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator);
    for (int i = 0; i < MAX_CALLTRACES; i++) {
        int samples = _methods[i]._call_count;
        if (samples == 0) break;

        jmethodID jmethod = _methods[i]._method;
        MethodSampleInfo *sampleInfo = info->add_methods();
        sampleInfo->set_call_count(samples);
        sampleInfo->set_jmethodid(jMethodIdToId(jmethod));
        methods.insert(jmethod);
    }
}

void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) {
    for (auto &jmethod: methodIds) {
        MethodInfo *methodInfo = info->add_methodinfos();
        fillMethodInfo(methodInfo, jmethod);
    }
}

<|endoftext|>


<commit_before>/*************************************************************************/
/*  gd_glue.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef MONO_GLUE_ENABLED

#include "core/io/marshalls.h"
#include "core/os/os.h"
#include "core/string/ustring.h"
#include "core/variant/array.h"
#include "core/variant/variant.h"
#include "core/variant/variant_parser.h"

#include "../mono_gd/gd_mono_cache.h"
#include "../mono_gd/gd_mono_marshal.h"
#include "../mono_gd/gd_mono_utils.h"

MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) {
	Variant ret;
	PackedByteArray varr = GDMonoMarshal::mono_array_to_PackedByteArray(p_bytes);
	Error err = decode_variant(ret, varr.ptr(), varr.size(), nullptr, p_allow_objects);
	if (err != OK) {
		ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
	}
	return GDMonoMarshal::variant_to_mono_object(ret);
}

MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) {
	Variant what = GDMonoMarshal::mono_object_to_variant(p_what);
	const Variant *args[1] = { &what };
	Callable::CallError ce;
	Variant ret = Variant::construct(Variant::Type(p_type), args, 1, ce);
	ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr);
	return GDMonoMarshal::variant_to_mono_object(ret);
}

int godot_icall_GD_hash(MonoObject *p_var) {
	return GDMonoMarshal::mono_object_to_variant(p_var).hash();
}

MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id) {
	return GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(ObjectID(p_instance_id)));
}

void godot_icall_GD_print(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	print_line(str);
}

void godot_icall_GD_printerr(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	print_error(str);
}

void godot_icall_GD_printraw(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	OS::get_singleton()->print("%s", str.utf8().get_data());
}

void godot_icall_GD_prints(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		if (i) {
			str += " ";
		}

		str += elem_str;
	}

	print_line(str);
}

void godot_icall_GD_printt(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		if (i) {
			str += "\t";
		}

		str += elem_str;
	}

	print_line(str);
}

float godot_icall_GD_randf() {
	return Math::randf();
}

uint32_t godot_icall_GD_randi() {
	return Math::rand();
}

void godot_icall_GD_randomize() {
	Math::randomize();
}

double godot_icall_GD_randf_range(double from, double to) {
	return Math::random(from, to);
}

int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) {
	return Math::random(from, to);
}

uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) {
	uint32_t ret = Math::rand_from_seed(&seed);
	*newSeed = seed;
	return ret;
}

void godot_icall_GD_seed(uint64_t p_seed) {
	Math::seed(p_seed);
}

MonoString *godot_icall_GD_str(MonoArray *p_what) {
	String str;
	Array what = GDMonoMarshal::mono_array_to_Array(p_what);

	for (int i = 0; i < what.size(); i++) {
		String os = what[i].operator String();

		if (i == 0) {
			str = os;
		} else {
			str += os;
		}
	}

	return GDMonoMarshal::mono_string_from_godot(str);
}

MonoObject *godot_icall_GD_str2var(MonoString *p_str) {
	Variant ret;

	VariantParser::StreamString ss;
	ss.s = GDMonoMarshal::mono_string_to_godot(p_str);

	String errs;
	int line;
	Error err = VariantParser::parse(&ss, ret, errs, line);
	if (err != OK) {
		String err_str = "Parse error at line " + itos(line) + ": " + errs + ".";
		ERR_PRINT(err_str);
		ret = err_str;
	}

	return GDMonoMarshal::variant_to_mono_object(ret);
}

MonoBoolean godot_icall_GD_type_exists(StringName *p_type) {
	StringName type = p_type ? *p_type : StringName();
	return ClassDB::class_exists(type);
}

void godot_icall_GD_pusherror(MonoString *p_str) {
	ERR_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
}

void godot_icall_GD_pushwarning(MonoString *p_str) {
	WARN_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
}

MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects) {
	Variant var = GDMonoMarshal::mono_object_to_variant(p_var);

	PackedByteArray barr;
	int len;
	Error err = encode_variant(var, nullptr, len, p_full_objects);
	ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).");

	barr.resize(len);
	encode_variant(var, barr.ptrw(), len, p_full_objects);

	return GDMonoMarshal::PackedByteArray_to_mono_array(barr);
}

MonoString *godot_icall_GD_var2str(MonoObject *p_var) {
	String vars;
	VariantWriter::write_to_string(GDMonoMarshal::mono_object_to_variant(p_var), vars);
	return GDMonoMarshal::mono_string_from_godot(vars);
}

uint32_t godot_icall_TypeToVariantType(MonoReflectionType *p_refl_type) {
	return (uint32_t)GDMonoMarshal::managed_to_variant_type(ManagedType::from_reftype(p_refl_type));
}

MonoObject *godot_icall_DefaultGodotTaskScheduler() {
	return GDMonoCache::cached_data.task_scheduler_handle->get_target();
}

void godot_register_gd_icalls() {
	mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var);
	mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert);
	mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash);
	mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id);
	mono_add_internal_call("Godot.GD::godot_icall_GD_pusherror", (void *)godot_icall_GD_pusherror);
	mono_add_internal_call("Godot.GD::godot_icall_GD_pushwarning", (void *)godot_icall_GD_pushwarning);
	mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw);
	mono_add_internal_call("Godot.GD::godot_icall_GD_prints", (void *)godot_icall_GD_prints);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printt", (void *)godot_icall_GD_printt);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randf", (void *)godot_icall_GD_randf);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randi", (void *)godot_icall_GD_randi);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randomize", (void *)godot_icall_GD_randomize);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randf_range", (void *)godot_icall_GD_randf_range);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randi_range", (void *)godot_icall_GD_randi_range);
	mono_add_internal_call("Godot.GD::godot_icall_GD_rand_seed", (void *)godot_icall_GD_rand_seed);
	mono_add_internal_call("Godot.GD::godot_icall_GD_seed", (void *)godot_icall_GD_seed);
	mono_add_internal_call("Godot.GD::godot_icall_GD_str", (void *)godot_icall_GD_str);
	mono_add_internal_call("Godot.GD::godot_icall_GD_str2var", (void *)godot_icall_GD_str2var);
	mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists);
	mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes);
	mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str);
	mono_add_internal_call("Godot.GD::godot_icall_TypeToVariantType", (void *)godot_icall_TypeToVariantType);

	// Dispatcher
	mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler);
}

#endif // MONO_GLUE_ENABLED
<commit_msg>Updated gd_glue.cpp to work with the latest changes in the variant refactoring<commit_after>/*************************************************************************/
/*  gd_glue.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef MONO_GLUE_ENABLED

#include "core/io/marshalls.h"
#include "core/os/os.h"
#include "core/string/ustring.h"
#include "core/variant/array.h"
#include "core/variant/variant.h"
#include "core/variant/variant_parser.h"

#include "../mono_gd/gd_mono_cache.h"
#include "../mono_gd/gd_mono_marshal.h"
#include "../mono_gd/gd_mono_utils.h"

MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) {
	Variant ret;
	PackedByteArray varr = GDMonoMarshal::mono_array_to_PackedByteArray(p_bytes);
	Error err = decode_variant(ret, varr.ptr(), varr.size(), nullptr, p_allow_objects);
	if (err != OK) {
		ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
	}
	return GDMonoMarshal::variant_to_mono_object(ret);
}

MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) {
	Variant what = GDMonoMarshal::mono_object_to_variant(p_what);
	const Variant *args[1] = { &what };
	Callable::CallError ce;
	Variant ret;
	Variant::construct(Variant::Type(p_type), ret, args, 1, ce);
	ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr);
	return GDMonoMarshal::variant_to_mono_object(ret);
}

int godot_icall_GD_hash(MonoObject *p_var) {
	return GDMonoMarshal::mono_object_to_variant(p_var).hash();
}

MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id) {
	return GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(ObjectID(p_instance_id)));
}

void godot_icall_GD_print(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	print_line(str);
}

void godot_icall_GD_printerr(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	print_error(str);
}

void godot_icall_GD_printraw(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		str += elem_str;
	}

	OS::get_singleton()->print("%s", str.utf8().get_data());
}

void godot_icall_GD_prints(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		if (i) {
			str += " ";
		}

		str += elem_str;
	}

	print_line(str);
}

void godot_icall_GD_printt(MonoArray *p_what) {
	String str;
	int length = mono_array_length(p_what);

	for (int i = 0; i < length; i++) {
		MonoObject *elem = mono_array_get(p_what, MonoObject *, i);

		MonoException *exc = nullptr;
		String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
			return;
		}

		if (i) {
			str += "\t";
		}

		str += elem_str;
	}

	print_line(str);
}

float godot_icall_GD_randf() {
	return Math::randf();
}

uint32_t godot_icall_GD_randi() {
	return Math::rand();
}

void godot_icall_GD_randomize() {
	Math::randomize();
}

double godot_icall_GD_randf_range(double from, double to) {
	return Math::random(from, to);
}

int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) {
	return Math::random(from, to);
}

uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) {
	uint32_t ret = Math::rand_from_seed(&seed);
	*newSeed = seed;
	return ret;
}

void godot_icall_GD_seed(uint64_t p_seed) {
	Math::seed(p_seed);
}

MonoString *godot_icall_GD_str(MonoArray *p_what) {
	String str;
	Array what = GDMonoMarshal::mono_array_to_Array(p_what);

	for (int i = 0; i < what.size(); i++) {
		String os = what[i].operator String();

		if (i == 0) {
			str = os;
		} else {
			str += os;
		}
	}

	return GDMonoMarshal::mono_string_from_godot(str);
}

MonoObject *godot_icall_GD_str2var(MonoString *p_str) {
	Variant ret;

	VariantParser::StreamString ss;
	ss.s = GDMonoMarshal::mono_string_to_godot(p_str);

	String errs;
	int line;
	Error err = VariantParser::parse(&ss, ret, errs, line);
	if (err != OK) {
		String err_str = "Parse error at line " + itos(line) + ": " + errs + ".";
		ERR_PRINT(err_str);
		ret = err_str;
	}

	return GDMonoMarshal::variant_to_mono_object(ret);
}

MonoBoolean godot_icall_GD_type_exists(StringName *p_type) {
	StringName type = p_type ? *p_type : StringName();
	return ClassDB::class_exists(type);
}

void godot_icall_GD_pusherror(MonoString *p_str) {
	ERR_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
}

void godot_icall_GD_pushwarning(MonoString *p_str) {
	WARN_PRINT(GDMonoMarshal::mono_string_to_godot(p_str));
}

MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects) {
	Variant var = GDMonoMarshal::mono_object_to_variant(p_var);

	PackedByteArray barr;
	int len;
	Error err = encode_variant(var, nullptr, len, p_full_objects);
	ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).");

	barr.resize(len);
	encode_variant(var, barr.ptrw(), len, p_full_objects);

	return GDMonoMarshal::PackedByteArray_to_mono_array(barr);
}

MonoString *godot_icall_GD_var2str(MonoObject *p_var) {
	String vars;
	VariantWriter::write_to_string(GDMonoMarshal::mono_object_to_variant(p_var), vars);
	return GDMonoMarshal::mono_string_from_godot(vars);
}

uint32_t godot_icall_TypeToVariantType(MonoReflectionType *p_refl_type) {
	return (uint32_t)GDMonoMarshal::managed_to_variant_type(ManagedType::from_reftype(p_refl_type));
}

MonoObject *godot_icall_DefaultGodotTaskScheduler() {
	return GDMonoCache::cached_data.task_scheduler_handle->get_target();
}

void godot_register_gd_icalls() {
	mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var);
	mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert);
	mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash);
	mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id);
	mono_add_internal_call("Godot.GD::godot_icall_GD_pusherror", (void *)godot_icall_GD_pusherror);
	mono_add_internal_call("Godot.GD::godot_icall_GD_pushwarning", (void *)godot_icall_GD_pushwarning);
	mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw);
	mono_add_internal_call("Godot.GD::godot_icall_GD_prints", (void *)godot_icall_GD_prints);
	mono_add_internal_call("Godot.GD::godot_icall_GD_printt", (void *)godot_icall_GD_printt);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randf", (void *)godot_icall_GD_randf);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randi", (void *)godot_icall_GD_randi);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randomize", (void *)godot_icall_GD_randomize);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randf_range", (void *)godot_icall_GD_randf_range);
	mono_add_internal_call("Godot.GD::godot_icall_GD_randi_range", (void *)godot_icall_GD_randi_range);
	mono_add_internal_call("Godot.GD::godot_icall_GD_rand_seed", (void *)godot_icall_GD_rand_seed);
	mono_add_internal_call("Godot.GD::godot_icall_GD_seed", (void *)godot_icall_GD_seed);
	mono_add_internal_call("Godot.GD::godot_icall_GD_str", (void *)godot_icall_GD_str);
	mono_add_internal_call("Godot.GD::godot_icall_GD_str2var", (void *)godot_icall_GD_str2var);
	mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists);
	mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes);
	mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str);
	mono_add_internal_call("Godot.GD::godot_icall_TypeToVariantType", (void *)godot_icall_TypeToVariantType);

	// Dispatcher
	mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler);
}

#endif // MONO_GLUE_ENABLED
<|endoftext|>


<commit_before>#include "catch.hpp"
#include "kangaru/kangaru.hpp"

namespace test_autowire_construct {

struct service1 {};
auto service_map(service1 const&) -> kgr::autowire;

struct service2 { friend auto service_map(service2 const&) -> kgr::autowire; };

TEST_CASE("autowire can construct a service", "[container]") {
	SECTION("Without dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		(void) kgr::container{}.service<kgr::autowired<service1>>();
	}

	SECTION("Without dependency with a friend function") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);
		(void) kgr::container{}.service<kgr::autowired<service2>>();
	}
}

}

namespace test_autowire_depencency {

int nb_s1_constructed;

struct service1 { service1() { nb_s1_constructed++; } };
auto service_map(service1 const&) -> kgr::autowire;

struct service2 {
	service1 s1;

	friend auto service_map(service2 const&) -> kgr::autowire;
};

TEST_CASE("autowire can have depencencies", "[container]") {
	nb_s1_constructed = 0;
	SECTION("Without dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		(void) kgr::container{}.service<kgr::autowired<service1>>();

		CHECK(nb_s1_constructed == 1);

		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);
		(void) kgr::container{}.service<kgr::autowired<service2>>();

		CHECK(nb_s1_constructed == 2);
	}
}

}

namespace test_autowire_single {

int nb_s1_constructed;

struct service1 { service1() { nb_s1_constructed++; } };
auto service_map(service1 const&) -> kgr::autowire_single;

struct service2 {
	service1& s1;

	friend auto service_map(service2 const&) -> kgr::autowire;
};

struct service3 {
	service3&& s3;

	friend auto service_map(service3 const&) -> kgr::autowire;
};

struct service4 {
	kgr::container forked;
	service2 s2;

	friend auto service_map(service4 const&) -> kgr::autowire;
};

struct service5 {
	kgr::container& ref;

	friend auto service_map(service5 const&) -> kgr::autowire_service<service5, kgr::autowire>;
};

TEST_CASE("autowire single behave as a single service", "[container]") {
	nb_s1_constructed = 0;

	REQUIRE(kgr::detail::is_single<kgr::autowired<service1>>::value);
	kgr::container c;

	SECTION("When injected as dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);

		auto& s1 = c.service<kgr::autowired<service1>>();
		CHECK(nb_s1_constructed == 1);

		auto s2 = c.service<kgr::autowired<service2>>();
		CHECK(nb_s1_constructed == 1);

		REQUIRE(&s1 == &s2.s1);
	}

	SECTION("Cannot inject itself into itself") {
		REQUIRE(!kgr::detail::is_service_valid<kgr::autowired<service3>>::value);
	}

	SECTION("Work with multiple dependencies") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service4>>::value);
		(void) kgr::container{}.service<kgr::autowired<service4>>();
	}
}

}
<commit_msg>Fixed autowire test with msvc<commit_after>#include "catch.hpp"
#include "kangaru/kangaru.hpp"

namespace test_autowire_construct {

struct service1 {};
auto service_map(service1 const&) -> kgr::autowire;

struct service2 { friend auto service_map(service2 const&) -> kgr::autowire; };

TEST_CASE("autowire can construct a service", "[container]") {
	SECTION("Without dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		(void) kgr::container{}.service<kgr::autowired<service1>>();
	}

	SECTION("Without dependency with a friend function") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);
		(void) kgr::container{}.service<kgr::autowired<service2>>();
	}
}

}

namespace test_autowire_depencency {

int nb_s1_constructed;

struct service1 { service1() { nb_s1_constructed++; } };
auto service_map(service1 const&) -> kgr::autowire;

struct service2 {
	service1 s1;

	friend auto service_map(service2 const&) -> kgr::autowire;
};

TEST_CASE("autowire can have depencencies", "[container]") {
	nb_s1_constructed = 0;
	SECTION("Without dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		(void) kgr::container{}.service<kgr::autowired<service1>>();

		CHECK(nb_s1_constructed == 1);

		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);
		(void) kgr::container{}.service<kgr::autowired<service2>>();

		CHECK(nb_s1_constructed == 2);
	}
}

}

namespace test_autowire_single {

int nb_s1_constructed;

struct service1 { service1() { nb_s1_constructed++; } };
auto service_map(service1 const&) -> kgr::autowire_single;

struct service2 {
	service1& s1;

	friend auto service_map(service2 const&) -> kgr::autowire;
};

struct service3 {
	service3&& s3;

	friend auto service_map(service3 const&) -> kgr::autowire;
};

struct service4 {
	service4(kgr::container f, service2 s) : forked{std::move(f)}, s2{std::move(s)} {}
	kgr::container forked;
	service2 s2;

	friend auto service_map(service4 const&) -> kgr::autowire;
};

struct service5 {
	kgr::container& ref;

	friend auto service_map(service5 const&) -> kgr::autowire_service<service5, kgr::autowire>;
};

TEST_CASE("autowire single behave as a single service", "[container]") {
	nb_s1_constructed = 0;

	REQUIRE(kgr::detail::is_single<kgr::autowired<service1>>::value);
	kgr::container c;

	SECTION("When injected as dependency") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value);
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value);

		auto& s1 = c.service<kgr::autowired<service1>>();
		CHECK(nb_s1_constructed == 1);

		auto s2 = c.service<kgr::autowired<service2>>();
		CHECK(nb_s1_constructed == 1);

		REQUIRE(&s1 == &s2.s1);
	}

	SECTION("Cannot inject itself into itself") {
		REQUIRE(!kgr::detail::is_service_valid<kgr::autowired<service3>>::value);
	}

	SECTION("Work with multiple dependencies") {
		REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service4>>::value);
		(void) kgr::container{}.service<kgr::autowired<service4>>();
	}
}

}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "catch.hpp"

#define DLL_SVM_SUPPORT

#include "dll/conv_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/rectifier_layer.hpp"
#include "dll/lcn_layer.hpp"
#include "dll/mp_layer.hpp"
#include "dll/avgp_layer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("unit/cdbn/lcn/mnist/1", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<9>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/2", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<7>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::visible<dll::unit_type::GAUSSIAN>, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->template layer_get<3>().learning_rate *= 3.0;
    dbn->template layer_get<3>().initial_momentum = 0.9;
    dbn->template layer_get<3>().momentum = 0.9;

    dbn->pretrain(dataset.training_images, 30);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.5); //Note: This is not very stable
}

TEST_CASE("unit/cdbn/lcn/mnist/3", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::mp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/4", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/5", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<7>::layer_t
            , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->template layer_get<3>().sigma = 2.0;

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("unit/cdbn/lcn/mnist/6", "[cdbn][lcn][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::avgp_layer_3d_desc<20, 12, 12, 2, 2, 1>::layer_t
            , dll::conv_rbm_desc_square<20, 6, 20, 4, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<3>::layer_t
            , dll::avgp_layer_3d_desc<20, 4, 4, 2, 2, 1>::layer_t
        >>::dbn_t;

    REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_pretrained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_trained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_pretrained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_trained());

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->template layer_get<1>().sigma = 1.0;
    dbn->template layer_get<4>().sigma = 1.0;

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);
}
<commit_msg>Test mixing LCN and dyn<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "catch.hpp"

#define DLL_SVM_SUPPORT

#include "dll/dyn_conv_rbm.hpp"
#include "dll/conv_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/rectifier_layer.hpp"
#include "dll/lcn_layer.hpp"
#include "dll/mp_layer.hpp"
#include "dll/avgp_layer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE("unit/cdbn/lcn/mnist/1", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<9>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/2", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<7>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::visible<dll::unit_type::GAUSSIAN>, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->template layer_get<3>().learning_rate *= 3.0;
    dbn->template layer_get<3>().initial_momentum = 0.9;
    dbn->template layer_get<3>().momentum = 0.9;

    dbn->pretrain(dataset.training_images, 30);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.5); //Note: This is not very stable
}

TEST_CASE("unit/cdbn/lcn/mnist/3", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::mp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/4", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}

TEST_CASE("unit/cdbn/lcn/mnist/5", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::rectifier_layer_desc<>::layer_t
            , dll::lcn_layer_desc<7>::layer_t
            , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->template layer_get<3>().sigma = 2.0;

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE("unit/cdbn/lcn/mnist/6", "[cdbn][lcn][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<5>::layer_t
            , dll::avgp_layer_3d_desc<20, 12, 12, 2, 2, 1>::layer_t
            , dll::conv_rbm_desc_square<20, 6, 20, 4, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t
            , dll::lcn_layer_desc<3>::layer_t
            , dll::avgp_layer_3d_desc<20, 4, 4, 2, 2, 1>::layer_t
        >>::dbn_t;

    REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_pretrained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_trained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_pretrained());
    REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_trained());

    auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->template layer_get<1>().sigma = 1.0;
    dbn->template layer_get<4>().sigma = 1.0;

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);
}

TEST_CASE("unit/cdbn/lcn/mnist/7", "[cdbn][lcn][svm][unit]") {
    using dbn_t =
        dll::dbn_desc<dll::dbn_layers<
              dll::dyn_conv_rbm_desc<dll::parallel_mode, dll::momentum>::layer_t
            , dll::dyn_conv_rbm_desc<dll::parallel_mode, dll::momentum>::layer_t
            , dll::lcn_layer_desc<9>::layer_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset_3d<std::vector, etl::dyn_matrix<double, 3>>(100);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->template init_layer<0>(1, 28, 28, 20, 12, 12);
    dbn->template init_layer<1>(20, 12, 12, 20, 10, 10);

    dbn->display();

    dbn->pretrain(dataset.training_images, 20);

    auto result = dbn->svm_train(dataset.training_images, dataset.training_labels);
    REQUIRE(result);

    auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.1);
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include <storage/cache.h>

using namespace cheesebase;

SCENARIO("Reading and writing to cache.")
{
  GIVEN("A cache")
  {
    Cache cache{ "test.db", OpenMode::create_always, 8 };
  }
}
<commit_msg>add simple Cache test case<commit_after>#include "catch.hpp"

#include <storage/cache.h>

using namespace cheesebase;

SCENARIO("Reading and writing to cache.")
{
  GIVEN("A cache")
  {
    Cache cache{ "test.db", OpenMode::create_always, 8 };

    WHEN("data is written to a page")
    {
      const PageNr page{ 5 };
      const size_t offset{ 100 };
      const std::string test{ "ABCDEFGHIJKLMNOP" };
      {
        auto p = cache.write(page);
        std::copy(test.begin(), test.end(), p.get_write().data() + offset);
      }

      THEN("same data can be read")
      {
        auto p = cache.read(page);
        REQUIRE(std::equal(test.begin(), test.end(), p.get().data() + offset));
      }

      AND_WHEN("many other pages are read")
      {
        for (PageNr i = 0; i < 20; ++i)
          cache.read(i);

        THEN("same data can sill be read")
        {
          auto p = cache.read(page);
          REQUIRE(std::equal(test.begin(), test.end(), p.get().data() + offset));
        }
      }
    }
  }
}
<|endoftext|>