<commit_before>/*
MIT License

Copyright (c) 2016 ME_Kun_Han

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.
*/

#include "rs_module_log.h"
#include <sstream>
#include <unistd.h>
#include <sys/time.h>
#include "rs_kernel_context.h"

namespace rs_log {
#define RS_LOG_MAX_LENGTH 4096

#define RS_LOG_LEVEL_INFO "info"
#define RS_LOG_LEVEL_VERBOSE "verbose"
#define RS_LOG_LEVEL_TRACE "trace"
#define RS_LOG_LEVEL_WARN "warn"
#define RS_LOG_LEVEL_ERROR "error"

    IRSLog::IRSLog() : msg(nullptr) {
        pid = getpid();
        msg = new char[4096];
    }

    IRSLog::~IRSLog() {
        rs_free_p(msg);
    }

    void IRSLog::info(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_INFO, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::verbose(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_VERBOSE, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::trace(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_TRACE, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::warn(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_WARN, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::error(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_ERROR, std::string(msg, static_cast<unsigned long>(size)));
    }

    void RSConsoleLog::log(int64_t cid, std::string level, std::string message) {
        std::stringstream ss;
        ss << "[" << pid << "]";
        ss << "[" << cid << "]";

        // time
        timeval tv = {0, 0};
        struct tm *time;
        if (gettimeofday(&tv, nullptr) == -1) {
            return;
        }

        if ((time = localtime(&tv.tv_sec)) == nullptr) {
            return;
        }

        // [2017-08-01 14:23:32.893]
        ss << "[" << 1900 + time->tm_year << "-" << 1 + time->tm_mon << "-"
           << time->tm_mday
           << " ";
        ss << time->tm_hour << ":" << time->tm_min << ":" << time->tm_sec << "."
           << (int) (tv.tv_usec / 1000.0) << "]";

        ss << "[" << level << "]";
        ss << ": " << message;

        std::cout << ss.str() << std::endl << std::flush;
    }
}
<commit_msg>fix compile error<commit_after>/*
MIT License

Copyright (c) 2016 ME_Kun_Han

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.
*/

#include "rs_module_log.h"
#include <sstream>
#include <unistd.h>
#include <sys/time.h>
#include <cstdarg>
#include "rs_kernel_context.h"

namespace rs_log {
#define RS_LOG_MAX_LENGTH 4096

#define RS_LOG_LEVEL_INFO "info"
#define RS_LOG_LEVEL_VERBOSE "verbose"
#define RS_LOG_LEVEL_TRACE "trace"
#define RS_LOG_LEVEL_WARN "warn"
#define RS_LOG_LEVEL_ERROR "error"

    IRSLog::IRSLog() : msg(nullptr) {
        pid = getpid();
        msg = new char[4096];
    }

    IRSLog::~IRSLog() {
        rs_free_p(msg);
    }

    void IRSLog::info(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_INFO, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::verbose(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_VERBOSE, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::trace(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_TRACE, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::warn(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_WARN, std::string(msg, static_cast<unsigned long>(size)));
    }

    void IRSLog::error(IRsReaderWriter *io, const char *fmt, ...) {
        va_list ap;
        va_start(ap, fmt);
        auto size = vsnprintf(msg, RS_LOG_MAX_LENGTH, fmt, ap);
        va_end(ap);

        auto cid = RsConnContext::getInstance()->get_id(io);

        log(cid, RS_LOG_LEVEL_ERROR, std::string(msg, static_cast<unsigned long>(size)));
    }

    void RSConsoleLog::log(int64_t cid, std::string level, std::string message) {
        std::stringstream ss;
        ss << "[" << pid << "]";
        ss << "[" << cid << "]";

        // time
        timeval tv = {0, 0};
        struct tm *time;
        if (gettimeofday(&tv, nullptr) == -1) {
            return;
        }

        if ((time = localtime(&tv.tv_sec)) == nullptr) {
            return;
        }

        // [2017-08-01 14:23:32.893]
        ss << "[" << 1900 + time->tm_year << "-" << 1 + time->tm_mon << "-"
           << time->tm_mday
           << " ";
        ss << time->tm_hour << ":" << time->tm_min << ":" << time->tm_sec << "."
           << (int) (tv.tv_usec / 1000.0) << "]";

        ss << "[" << level << "]";
        ss << ": " << message;

        std::cout << ss.str() << std::endl << std::flush;
    }
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#define N 7

int add(int n){
    if (n <= 0)
        return 0;
    return n + add(n-1);
}

int main(int argc, char *argv[]){

    printf("R: %i\n", add(N));

    return EXIT_SUCCESS;
}
<commit_msg>Delete add.cpp<commit_after><|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.
//
// Author: nadavs@google.com <Nadav Samet>

#include "rpcz/server.h"
#include <signal.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/signal.h>
#include <iostream>
#include <utility>

#include "boost/bind.hpp"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/stubs/common.h"
#include "zmq.hpp"

#include "rpcz/callback.h"
#include "rpcz/connection_manager.h"
#include "rpcz/function_server.h"
#include "rpcz/logging.h"
#include "rpcz/macros.h"
#include "rpcz/rpc.h"
#include "rpcz/reactor.h"
#include "rpcz/service.h"
#include "rpcz/zmq_utils.h"
#include "rpcz/rpcz.pb.h"

namespace rpcz {

class ServerChannelImpl;

class ServerImpl {
 public:
  ServerImpl(zmq::socket_t* socket, FunctionServer* function_server);

  ~ServerImpl();

  void Start();

  void RegisterService(RpcService *service, const std::string& name);

 private:
  void HandleFunctionResponse(zmq::socket_t* fs_socket);

  void HandleRequestWorker(MessageVector* routes_,
                           MessageVector* data_,
                           FunctionServer::ReplyFunction reply);

  void HandleRequest(zmq::socket_t* fs_socket);

  zmq::socket_t* socket_;
  FunctionServer* function_server_;
  typedef std::map<std::string, rpcz::RpcService*> RpcServiceMap;
  RpcServiceMap service_map_;
  DISALLOW_COPY_AND_ASSIGN(ServerImpl);
};

class ServerChannelImpl : public ServerChannel {
 public:
  ServerChannelImpl(MessageVector* routes,
                    zmq::message_t* request_id,
                    FunctionServer::ReplyFunction reply)
      : routes_(routes), request_id_(request_id),
        reply_(reply) { }

  virtual void Send(const google::protobuf::Message& response) {
    RpcResponseHeader generic_rpc_response;
    int msg_size = response.ByteSize();
    scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
    if (!response.SerializeToArray(payload->data(), msg_size)) {
      throw InvalidMessageError("Invalid response message");
    }
    SendGenericResponse(generic_rpc_response,
                        payload.release());
  }

  virtual void Send0(const std::string& response) {
    RpcResponseHeader generic_rpc_response;
    SendGenericResponse(generic_rpc_response,
                        StringToMessage(response));
  }

  virtual void SendError(int application_error,
                         const std::string& error_message="") {
    RpcResponseHeader generic_rpc_response;
    zmq::message_t* payload = new zmq::message_t();
    generic_rpc_response.set_status(status::APPLICATION_ERROR);
    generic_rpc_response.set_application_error(application_error);
    if (!error_message.empty()) {
      generic_rpc_response.set_error(error_message);
    }
    SendGenericResponse(generic_rpc_response,
                        payload);
  }

 private:
  scoped_ptr<MessageVector> routes_;
  scoped_ptr<zmq::message_t> request_id_;
  scoped_ptr<google::protobuf::Message> request_;
  FunctionServer::ReplyFunction reply_;

  // Sends the response back to a function server through the reply function.
  // Takes ownership of the provided payload message.
  void SendGenericResponse(const RpcResponseHeader& generic_rpc_response,
                           zmq::message_t* payload) {
    size_t msg_size = generic_rpc_response.ByteSize();
    zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
    CHECK(generic_rpc_response.SerializeToArray(
            zmq_response_message->data(),
            msg_size));

    routes_->push_back(request_id_.release());
    routes_->push_back(zmq_response_message);
    routes_->push_back(payload);
    reply_(routes_.get());
  }

  friend class ProtoRpcService;
};

class ProtoRpcService : public RpcService {
 public:
  explicit ProtoRpcService(Service* service) : service_(service) {
  }

  virtual void DispatchRequest(const std::string& method,
                               const void* payload, size_t payload_len,
                               ServerChannel* channel_) {
    scoped_ptr<ServerChannelImpl> channel(
        static_cast<ServerChannelImpl*>(channel_));

    const ::google::protobuf::MethodDescriptor* descriptor =
        service_->GetDescriptor()->FindMethodByName(
            method);
    if (descriptor == NULL) {
      // Invalid method name
      DLOG(INFO) << "Invalid method name: " << method,
      channel->SendError(application_error::NO_SUCH_METHOD);
      return;
    }
    channel->request_.reset(CHECK_NOTNULL(
            service_->GetRequestPrototype(descriptor).New()));
    if (!channel->request_->ParseFromArray(payload, payload_len)) {
      DLOG(INFO) << "Failed to parse request.";
      // Invalid proto;
      channel->SendError(application_error::INVALID_MESSAGE);
      return;
    }

    service_->CallMethod(descriptor,
                         *channel->request_,
                         channel.release());
  }

 private:
  Service* service_;
};

ServerImpl::ServerImpl(zmq::socket_t* socket, FunctionServer* function_server)
  : socket_(socket), function_server_(function_server) {}

void ServerImpl::Start() {
  // The reactor owns all sockets.
  Reactor reactor;
  zmq::socket_t* fs_socket = function_server_->GetConnectedSocket();
  reactor.AddSocket(socket_, NewPermanentCallback(
          this, &ServerImpl::HandleRequest, fs_socket));
  reactor.AddSocket(fs_socket,
                    NewPermanentCallback(
                        this, &ServerImpl::HandleFunctionResponse,
                        fs_socket));
  reactor.Loop();
}

void ServerImpl::RegisterService(RpcService *rpc_service,
                                 const std::string& name) {
  service_map_[name] = rpc_service;
}

void ServerImpl::HandleFunctionResponse(zmq::socket_t* fs_socket) {
  MessageVector data;
  CHECK(ReadMessageToVector(fs_socket, &data));
  data.erase_first();
  WriteVectorToSocket(socket_, data);
}

void ServerImpl::HandleRequestWorker(MessageVector* routes_,
                                     MessageVector* data_,
                                     FunctionServer::ReplyFunction reply) {
  // We are responsible to delete routes and data (and the pointers they
  // contain, so first wrap them in scoped_ptr's.
  scoped_ptr<ServerChannel> channel(new ServerChannelImpl(
          routes_,
          data_->release(0),
          reply));

  scoped_ptr<MessageVector> data(data_);
  CHECK_EQ(3u, data->size());
  zmq::message_t& request = (*data)[1];
  zmq::message_t& payload = (*data)[2];

  RpcRequestHeader rpc_request_header;
  if (!rpc_request_header.ParseFromArray(request.data(), request.size())) {
    // Handle bad RPC.
    DLOG(INFO) << "Received bad header.";
    channel->SendError(application_error::INVALID_HEADER);
    return;
  };
  RpcServiceMap::const_iterator service_it = service_map_.find(
      rpc_request_header.service());
  if (service_it == service_map_.end()) {
    // Handle invalid service.
    DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
    channel->SendError(application_error::NO_SUCH_SERVICE);
    return;
  }
  rpcz::RpcService* service = service_it->second;
  service->DispatchRequest(rpc_request_header.method(), payload.data(),
                           payload.size(),
                           channel.release());
}

void ServerImpl::HandleRequest(zmq::socket_t* fs_socket) {
  scoped_ptr<MessageVector> routes(new MessageVector());
  scoped_ptr<MessageVector> data(new MessageVector());
  ReadMessageToVector(socket_, routes.get(), data.get());
  if (data->size() != 3) {
    DLOG(INFO) << "Dropping invalid requests.";
    return;
  }
  FunctionServer::AddFunction(
      fs_socket,
      boost::bind(&ServerImpl::HandleRequestWorker,
                  this, routes.release(), data.release(), _1));
}

ServerImpl::~ServerImpl() {
  DeleteContainerSecondPointer(service_map_.begin(),
                               service_map_.end());
}

Server::Server(zmq::socket_t* socket, EventManager* event_manager)
  : server_impl_(new ServerImpl(socket, event_manager->GetFunctionServer())) {
}

Server::~Server() {
}

void Server::Start() {
  server_impl_->Start();
}

void Server::RegisterService(rpcz::Service *service) {
  RegisterService(service,
                  service->GetDescriptor()->name());
}

void Server::RegisterService(rpcz::Service *service, const std::string& name) {
  RegisterService(new ProtoRpcService(service),
                  name);
}

void Server::RegisterService(rpcz::RpcService *rpc_service,
                             const std::string& name) {
  server_impl_->RegisterService(rpc_service,
                                name);
}

}  // namespace
<commit_msg>fix a bug that caused segfaults on linux (order of argument evaluation in c++ is unspecified)<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.
//
// Author: nadavs@google.com <Nadav Samet>

#include "rpcz/server.h"
#include <signal.h>
#include <string.h>
#include <sys/errno.h>
#include <sys/signal.h>
#include <iostream>
#include <utility>

#include "boost/bind.hpp"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "google/protobuf/stubs/common.h"
#include "zmq.hpp"

#include "rpcz/callback.h"
#include "rpcz/connection_manager.h"
#include "rpcz/function_server.h"
#include "rpcz/logging.h"
#include "rpcz/macros.h"
#include "rpcz/rpc.h"
#include "rpcz/reactor.h"
#include "rpcz/service.h"
#include "rpcz/zmq_utils.h"
#include "rpcz/rpcz.pb.h"

namespace rpcz {

class ServerChannelImpl;

class ServerImpl {
 public:
  ServerImpl(zmq::socket_t* socket, FunctionServer* function_server);

  ~ServerImpl();

  void Start();

  void RegisterService(RpcService *service, const std::string& name);

 private:
  void HandleFunctionResponse(zmq::socket_t* fs_socket);

  void HandleRequestWorker(MessageVector* routes_,
                           MessageVector* data_,
                           FunctionServer::ReplyFunction reply);

  void HandleRequest(zmq::socket_t* fs_socket);

  zmq::socket_t* socket_;
  FunctionServer* function_server_;
  typedef std::map<std::string, rpcz::RpcService*> RpcServiceMap;
  RpcServiceMap service_map_;
  DISALLOW_COPY_AND_ASSIGN(ServerImpl);
};

class ServerChannelImpl : public ServerChannel {
 public:
  ServerChannelImpl(MessageVector* routes,
                    zmq::message_t* request_id,
                    FunctionServer::ReplyFunction reply)
      : routes_(routes), request_id_(request_id),
        reply_(reply) { }

  virtual void Send(const google::protobuf::Message& response) {
    RpcResponseHeader generic_rpc_response;
    int msg_size = response.ByteSize();
    scoped_ptr<zmq::message_t> payload(new zmq::message_t(msg_size));
    if (!response.SerializeToArray(payload->data(), msg_size)) {
      throw InvalidMessageError("Invalid response message");
    }
    SendGenericResponse(generic_rpc_response,
                        payload.release());
  }

  virtual void Send0(const std::string& response) {
    RpcResponseHeader generic_rpc_response;
    SendGenericResponse(generic_rpc_response,
                        StringToMessage(response));
  }

  virtual void SendError(int application_error,
                         const std::string& error_message="") {
    RpcResponseHeader generic_rpc_response;
    zmq::message_t* payload = new zmq::message_t();
    generic_rpc_response.set_status(status::APPLICATION_ERROR);
    generic_rpc_response.set_application_error(application_error);
    if (!error_message.empty()) {
      generic_rpc_response.set_error(error_message);
    }
    SendGenericResponse(generic_rpc_response,
                        payload);
  }

 private:
  scoped_ptr<MessageVector> routes_;
  scoped_ptr<zmq::message_t> request_id_;
  scoped_ptr<google::protobuf::Message> request_;
  FunctionServer::ReplyFunction reply_;

  // Sends the response back to a function server through the reply function.
  // Takes ownership of the provided payload message.
  void SendGenericResponse(const RpcResponseHeader& generic_rpc_response,
                           zmq::message_t* payload) {
    size_t msg_size = generic_rpc_response.ByteSize();
    zmq::message_t* zmq_response_message = new zmq::message_t(msg_size);
    CHECK(generic_rpc_response.SerializeToArray(
            zmq_response_message->data(),
            msg_size));

    routes_->push_back(request_id_.release());
    routes_->push_back(zmq_response_message);
    routes_->push_back(payload);
    reply_(routes_.get());
  }

  friend class ProtoRpcService;
};

class ProtoRpcService : public RpcService {
 public:
  explicit ProtoRpcService(Service* service) : service_(service) {
  }

  virtual void DispatchRequest(const std::string& method,
                               const void* payload, size_t payload_len,
                               ServerChannel* channel_) {
    scoped_ptr<ServerChannelImpl> channel(
        static_cast<ServerChannelImpl*>(channel_));

    const ::google::protobuf::MethodDescriptor* descriptor =
        service_->GetDescriptor()->FindMethodByName(
            method);
    if (descriptor == NULL) {
      // Invalid method name
      DLOG(INFO) << "Invalid method name: " << method,
      channel->SendError(application_error::NO_SUCH_METHOD);
      return;
    }
    channel->request_.reset(CHECK_NOTNULL(
            service_->GetRequestPrototype(descriptor).New()));
    if (!channel->request_->ParseFromArray(payload, payload_len)) {
      DLOG(INFO) << "Failed to parse request.";
      // Invalid proto;
      channel->SendError(application_error::INVALID_MESSAGE);
      return;
    }
    ServerChannelImpl* channel_ptr = channel.release();
    service_->CallMethod(descriptor,
                         *channel_ptr->request_,
                         channel_ptr);
  }

 private:
  Service* service_;
};

ServerImpl::ServerImpl(zmq::socket_t* socket, FunctionServer* function_server)
  : socket_(socket), function_server_(function_server) {}

void ServerImpl::Start() {
  // The reactor owns all sockets.
  Reactor reactor;
  zmq::socket_t* fs_socket = function_server_->GetConnectedSocket();
  reactor.AddSocket(socket_, NewPermanentCallback(
          this, &ServerImpl::HandleRequest, fs_socket));
  reactor.AddSocket(fs_socket,
                    NewPermanentCallback(
                        this, &ServerImpl::HandleFunctionResponse,
                        fs_socket));
  reactor.Loop();
}

void ServerImpl::RegisterService(RpcService *rpc_service,
                                 const std::string& name) {
  service_map_[name] = rpc_service;
}

void ServerImpl::HandleFunctionResponse(zmq::socket_t* fs_socket) {
  MessageVector data;
  CHECK(ReadMessageToVector(fs_socket, &data));
  data.erase_first();
  WriteVectorToSocket(socket_, data);
}

void ServerImpl::HandleRequestWorker(MessageVector* routes_,
                                     MessageVector* data_,
                                     FunctionServer::ReplyFunction reply) {
  // We are responsible to delete routes and data (and the pointers they
  // contain, so first wrap them in scoped_ptr's.
  scoped_ptr<ServerChannel> channel(new ServerChannelImpl(
          routes_,
          data_->release(0),
          reply));

  scoped_ptr<MessageVector> data(data_);
  CHECK_EQ(3u, data->size());
  zmq::message_t& request = (*data)[1];
  zmq::message_t& payload = (*data)[2];

  RpcRequestHeader rpc_request_header;
  if (!rpc_request_header.ParseFromArray(request.data(), request.size())) {
    // Handle bad RPC.
    DLOG(INFO) << "Received bad header.";
    channel->SendError(application_error::INVALID_HEADER);
    return;
  };
  RpcServiceMap::const_iterator service_it = service_map_.find(
      rpc_request_header.service());
  if (service_it == service_map_.end()) {
    // Handle invalid service.
    DLOG(INFO) << "Invalid service: " << rpc_request_header.service();
    channel->SendError(application_error::NO_SUCH_SERVICE);
    return;
  }
  rpcz::RpcService* service = service_it->second;
  service->DispatchRequest(rpc_request_header.method(), payload.data(),
                           payload.size(),
                           channel.release());
}

void ServerImpl::HandleRequest(zmq::socket_t* fs_socket) {
  scoped_ptr<MessageVector> routes(new MessageVector());
  scoped_ptr<MessageVector> data(new MessageVector());
  ReadMessageToVector(socket_, routes.get(), data.get());
  if (data->size() != 3) {
    DLOG(INFO) << "Dropping invalid requests.";
    return;
  }
  FunctionServer::AddFunction(
      fs_socket,
      boost::bind(&ServerImpl::HandleRequestWorker,
                  this, routes.release(), data.release(), _1));
}

ServerImpl::~ServerImpl() {
  DeleteContainerSecondPointer(service_map_.begin(),
                               service_map_.end());
}

Server::Server(zmq::socket_t* socket, EventManager* event_manager)
  : server_impl_(new ServerImpl(socket, event_manager->GetFunctionServer())) {
}

Server::~Server() {
}

void Server::Start() {
  server_impl_->Start();
}

void Server::RegisterService(rpcz::Service *service) {
  RegisterService(service,
                  service->GetDescriptor()->name());
}

void Server::RegisterService(rpcz::Service *service, const std::string& name) {
  RegisterService(new ProtoRpcService(service),
                  name);
}

void Server::RegisterService(rpcz::RpcService *rpc_service,
                             const std::string& name) {
  server_impl_->RegisterService(rpc_service,
                                name);
}

}  // namespace
<|endoftext|>


<commit_before>// Rust cycle collector. Temporary, but will probably stick around for some
// time until LLVM's GC infrastructure is more mature.

#include <cstdio>
#include <cstdlib>
#include <map>
#include <vector>
#include "rust_gc.h"
#include "rust_internal.h"
#include "rust_shape.h"
#include "rust_task.h"

#undef DPRINT
#define DPRINT(fmt,...)     fprintf(stderr, fmt, ##__VA_ARGS__)

namespace cc {

void
do_cc(rust_task *task) {
    std::map<void *,type_desc *>::iterator begin(task->local_allocs.begin());
    std::map<void *,type_desc *>::iterator end(task->local_allocs.end());
    while (begin != end) {
        void *p = begin->first;
        type_desc *tydesc = begin->second;

        DPRINT("marking allocation: %p, tydesc=%p\n", p, tydesc);

        // Prevents warnings for now
        (void)p;
        (void)tydesc;
#if 0
        shape::arena arena;
        shape::type_param *params =
            shape::type_param::from_tydesc(tydesc, arena);
        mark mark(task, true, tydesc->shape, params, tydesc->shape_tables, p);
        mark.walk();
#endif

        ++begin;
    }
}

void
maybe_cc(rust_task *task) {
    // FIXME: We ought to lock this.
    static int zeal = -1;
    if (zeal == -1) {
        char *ev = getenv("RUST_CC_ZEAL");
        zeal = ev && ev[0] != '\0' && ev[0] != '0';
    }

    if (zeal)
        do_cc(task);
}

}   // end namespace cc

<commit_msg>rt: First stab at computing internal reference counts<commit_after>// Rust cycle collector. Temporary, but will probably stick around for some
// time until LLVM's GC infrastructure is more mature.

#include "rust_gc.h"
#include "rust_internal.h"
#include "rust_shape.h"
#include "rust_task.h"
#include <cstdio>
#include <cstdlib>
#include <map>
#include <vector>
#include <stdint.h>

#undef DPRINT
#define DPRINT(fmt,...)     fprintf(stderr, fmt, ##__VA_ARGS__)

namespace cc {

// Internal reference count computation

typedef std::map<void *,uintptr_t> irc_map;

class irc : public shape::data<irc,shape::ptr> {
    friend class shape::data<irc,shape::ptr>;

    irc_map ircs;

    irc(const irc &other, const shape::ptr &in_dp)
    : shape::data<irc,shape::ptr>(other.task, other.align, other.sp,
                                  other.params, other.tables, in_dp),
      ircs(other.ircs) {}

    irc(const irc &other,
        const uint8_t *in_sp,
        const shape::type_param *in_params,
        const rust_shape_tables *in_tables = NULL)
    : shape::data<irc,shape::ptr>(other.task,
                                  other.align,
                                  in_sp,
                                  in_params,
                                  in_tables ? in_tables : other.tables,
                                  other.dp),
      ircs(other.ircs) {}

    irc(const irc &other,
        const uint8_t *in_sp,
        const shape::type_param *in_params,
        const rust_shape_tables *in_tables,
        shape::ptr in_dp)
    : shape::data<irc,shape::ptr>(other.task,
                                  other.align,
                                  in_sp,
                                  in_params,
                                  in_tables,
                                  in_dp),
      ircs(other.ircs) {}

    irc(rust_task *in_task,
        bool in_align,
        const uint8_t *in_sp,
        const shape::type_param *in_params,
        const rust_shape_tables *in_tables,
        uint8_t *in_data,
        irc_map &in_ircs)
    : shape::data<irc,shape::ptr>(in_task, in_align, in_sp, in_params,
                                  in_tables, in_data),
      ircs(in_ircs) {}

    void walk_vec(bool is_pod, uint16_t sp_size) {
        if (is_pod || shape::get_dp<void *>(dp) == NULL)
            return;     // There can't be any outbound pointers from this.

        std::pair<uint8_t *,uint8_t *> data_range(get_vec_data_range(dp));
        if (data_range.second - data_range.first > 10000)
            abort();    // FIXME: Temporary sanity check.

        irc sub(*this, data_range.first);
        shape::ptr data_end = sub.end_dp = data_range.second;
        while (sub.dp < data_end) {
            sub.walk_reset();
            align = true;
        }
    }

    void walk_tag(shape::tag_info &tinfo, uint32_t tag_variant) {
        shape::data<irc,shape::ptr>::walk_variant(tinfo, tag_variant);
    }

    void walk_box() {
        shape::data<irc,shape::ptr>::walk_box_contents();
    }

    void walk_fn() {
        shape::data<irc,shape::ptr>::walk_fn_contents(dp);
    }

    void walk_obj() {
        shape::data<irc,shape::ptr>::walk_obj_contents(dp);
    }

    void walk_res(const shape::rust_fn *dtor, unsigned n_params,
                  const shape::type_param *params, const uint8_t *end_sp,
                  bool live) {
        while (this->sp != end_sp) {
            this->walk();
            align = true;
        }
    }

    void walk_subcontext(irc &sub) { sub.walk(); }

    void walk_box_contents(irc &sub, shape::ptr &ref_count_dp) {
        if (!ref_count_dp)
            return;

        // Bump the internal reference count of the box.
        if (ircs.find((void *)dp) == ircs.end())
            ircs[(void *)dp] = 1;
        else
            ++ircs[(void *)dp];

        // Do not traverse the contents of this box; it's in the allocation
        // somewhere, so we're guaranteed to come back to it (if we haven't
        // traversed it already).
    }

    void walk_struct(const uint8_t *end_sp) {
        while (this->sp != end_sp) {
            this->walk();
            align = true;
        }
    }

    void walk_variant(shape::tag_info &tinfo, uint32_t variant_id,
                      const std::pair<const uint8_t *,const uint8_t *>
                      variant_ptr_and_end);

    template<typename T>
    inline void walk_number() { /* no-op */ }

public:
    static void compute_ircs(rust_task *task, irc_map &ircs);
};

void
irc::walk_variant(shape::tag_info &tinfo, uint32_t variant_id,
                  const std::pair<const uint8_t *,const uint8_t *>
                  variant_ptr_and_end) {
    irc sub(*this, variant_ptr_and_end.first, tinfo.params);

    assert(variant_id < 256);   // FIXME: Temporary sanity check.

    const uint8_t *variant_end = variant_ptr_and_end.second;
    while (sub.sp < variant_end) {
        sub.walk();
        align = true;
    }
}

void
irc::compute_ircs(rust_task *task, irc_map &ircs) {
    std::map<void *,type_desc *>::iterator begin(task->local_allocs.begin()),
                                           end(task->local_allocs.end());
    while (begin != end) {
        uint8_t *p = reinterpret_cast<uint8_t *>(begin->first);
        type_desc *tydesc = begin->second;

        DPRINT("determining internal ref counts: %p, tydesc=%p\n", p, tydesc);

        // Prevents warnings for now
        shape::arena arena;
        shape::type_param *params =
            shape::type_param::from_tydesc(tydesc, arena);
        irc irc(task, true, tydesc->shape, params, tydesc->shape_tables, p,
                ircs);
        irc.walk();

        ++begin;
    }
}

void
do_cc(rust_task *task) {
    irc_map ircs;
    irc::compute_ircs(task, ircs);
}

void
maybe_cc(rust_task *task) {
    // FIXME: We ought to lock this.
    static int zeal = -1;
    if (zeal == -1) {
        char *ev = getenv("RUST_CC_ZEAL");
        zeal = ev && ev[0] != '\0' && ev[0] != '0';
    }

    if (zeal)
        do_cc(task);
}

}   // end namespace cc

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/widget/tooltip_window_gtk.h"

#include "base/utf_string_conversions.h"

namespace views {

TooltipWindowGtk::TooltipWindowGtk(GtkWidget* widget)
    : host_(widget),
      window_(NULL),
      alignment_(NULL),
      label_(NULL) {
  Init();
}

TooltipWindowGtk::~TooltipWindowGtk() {
  if (window_)
    gtk_widget_destroy(window_);
}

void TooltipWindowGtk::SetTooltipText(const std::wstring& text) {
  const std::string& utf8 = WideToUTF8(text);

  gtk_label_set_text(label(), utf8.c_str());
  // Setting the text in a label doesn't force recalculating wrap position.
  // We force recalculating wrap position by resetting the max width.
  gtk_label_set_max_width_chars(label(), 2999);
  gtk_label_set_max_width_chars(label(), 3000);
}

void  TooltipWindowGtk::Init() {
  // Creates and setup tooltip window.
  window_ = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_window_set_type_hint(GTK_WINDOW(window_), GDK_WINDOW_TYPE_HINT_TOOLTIP);
  gtk_widget_set_app_paintable(window_, TRUE);
  gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
  gtk_widget_set_name(window_, "gtk-tooltip");

  GdkColormap* rgba_colormap =
      gdk_screen_get_rgba_colormap(gdk_screen_get_default());
  if (rgba_colormap)
    gtk_widget_set_colormap(window_, rgba_colormap);

  g_signal_connect(G_OBJECT(window_), "expose-event",
                   G_CALLBACK(&OnPaintThunk), this);
  g_signal_connect(G_OBJECT(window_), "style-set",
                   G_CALLBACK(&OnStyleSetThunk), this);

  alignment_ = gtk_alignment_new(0.5, 0.5, 1.0, 1.0);
  gtk_container_add(GTK_CONTAINER(window_), alignment_);
  gtk_widget_show(alignment_);

  label_ = gtk_label_new("");
  gtk_label_set_line_wrap(GTK_LABEL(label_), TRUE);
  gtk_label_set_max_width_chars(GTK_LABEL(label_), 3000);
  gtk_container_add(GTK_CONTAINER(alignment_), label_);
  gtk_widget_show(label_);

  // Associates the tooltip window with given widget
  gtk_widget_set_tooltip_window(host_, GTK_WINDOW(window_));
}

// Paints our customized tooltip window.
gboolean TooltipWindowGtk::OnPaint(GtkWidget* widget, GdkEventExpose* event) {
  gtk_paint_flat_box(widget->style,
      widget->window,
      GTK_STATE_NORMAL,
      GTK_SHADOW_OUT,
      NULL,
      widget,
      "tooltip",
      0, 0,
      widget->allocation.width,
      widget->allocation.height);

  return FALSE;
}

// Style change handler.
void TooltipWindowGtk::OnStyleSet(GtkWidget* widget,
                                  GtkStyle* previous_style) {
  gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_),
      widget->style->ythickness,
      widget->style->ythickness,
      widget->style->xthickness,
      widget->style->xthickness);

  gtk_widget_queue_draw(widget);
}

}  // namespace views
<commit_msg>Fix tooltip wrap problem per chromium-os:4042<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "views/widget/tooltip_window_gtk.h"

#include "base/utf_string_conversions.h"

namespace views {

TooltipWindowGtk::TooltipWindowGtk(GtkWidget* widget)
    : host_(widget),
      window_(NULL),
      alignment_(NULL),
      label_(NULL) {
  Init();
}

TooltipWindowGtk::~TooltipWindowGtk() {
  if (window_)
    gtk_widget_destroy(window_);
}

void TooltipWindowGtk::SetTooltipText(const std::wstring& text) {
  const std::string& utf8 = WideToUTF8(text);

  gtk_label_set_text(label(), utf8.c_str());
}

void  TooltipWindowGtk::Init() {
  // Creates and setup tooltip window.
  window_ = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_window_set_type_hint(GTK_WINDOW(window_), GDK_WINDOW_TYPE_HINT_TOOLTIP);
  gtk_widget_set_app_paintable(window_, TRUE);
  gtk_window_set_resizable(GTK_WINDOW(window_), FALSE);
  gtk_widget_set_name(window_, "gtk-tooltip");

  GdkColormap* rgba_colormap =
      gdk_screen_get_rgba_colormap(gdk_screen_get_default());
  if (rgba_colormap)
    gtk_widget_set_colormap(window_, rgba_colormap);

  g_signal_connect(G_OBJECT(window_), "expose-event",
                   G_CALLBACK(&OnPaintThunk), this);
  g_signal_connect(G_OBJECT(window_), "style-set",
                   G_CALLBACK(&OnStyleSetThunk), this);

  alignment_ = gtk_alignment_new(0.5, 0.5, 1.0, 1.0);
  gtk_container_add(GTK_CONTAINER(window_), alignment_);
  gtk_widget_show(alignment_);

  label_ = gtk_label_new("");
  gtk_label_set_line_wrap(GTK_LABEL(label_), TRUE);
  gtk_container_add(GTK_CONTAINER(alignment_), label_);
  gtk_widget_show(label_);

  // Associates the tooltip window with given widget
  gtk_widget_set_tooltip_window(host_, GTK_WINDOW(window_));
}

// Paints our customized tooltip window.
gboolean TooltipWindowGtk::OnPaint(GtkWidget* widget, GdkEventExpose* event) {
  gtk_paint_flat_box(widget->style,
      widget->window,
      GTK_STATE_NORMAL,
      GTK_SHADOW_OUT,
      NULL,
      widget,
      "tooltip",
      0, 0,
      widget->allocation.width,
      widget->allocation.height);

  return FALSE;
}

// Style change handler.
void TooltipWindowGtk::OnStyleSet(GtkWidget* widget,
                                  GtkStyle* previous_style) {
  gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_),
      widget->style->ythickness,
      widget->style->ythickness,
      widget->style->xthickness,
      widget->style->xthickness);

  gtk_widget_queue_draw(widget);
}

}  // namespace views
<|endoftext|>


<commit_before>//
//!	@file	tcp_socket.cpp
//!	@brief	tcp session socket class
//
//	copyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD.
//	mail:
//
//	Distributed under the Boost Software License, Version 1.0.(See accompanying
//	file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/thread/thread.hpp>

#include "tcp_socket.h"
#include "logger.h"

namespace l7vs{

	//! construcor
	tcp_socket::tcp_socket(boost::asio::io_service& io):
		my_socket(io),
		open_flag(false){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::tcp_socket", __FILE__, __LINE__ );

	}

	//! destructor
	tcp_socket::~tcp_socket(){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::~tcp_socket", __FILE__, __LINE__ );
	}

	//! get reference control socket
	//! @return			reference control socket
	boost::asio::ip::tcp::socket& tcp_socket::get_socket(){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::get_socket", __FILE__, __LINE__ );
		return my_socket;
	}

	//! connect socket
	//! @param[in]		connect_endpoint is connection endpoint
	//! @param[out]		ec is reference error code object
	//! @return 		true is connect
	//! @return 		false is connect failure
	bool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::connect", __FILE__, __LINE__ );

        rw_scoped_lock scope_lock(close_mutex);

		if(!open_flag){
			my_socket.connect(connect_endpoint,ec);
			if(!ec){
				open_flag = true;
				//----Debug log----------------------------------------------------------------------
				if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){
					std::stringstream buf;
					buf << "Thread ID[";
					buf << boost::this_thread::get_id();
					buf << "] tcp_socket::connect [";
					buf << connect_endpoint;
					buf << "]";
					Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
				}
				//----Debug log----------------------------------------------------------------------
			}else{
				open_flag = false;
			}
		}
		return open_flag;
	}

	//! accept socket
	void tcp_socket::accept(){
        rw_scoped_lock scope_lock(close_mutex);

		open_flag = true;
		//----Debug log----------------------------------------------------------------------
		if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){
			boost::system::error_code ec;
			std::stringstream buf;
			buf << "Thread ID[";
			buf << boost::this_thread::get_id();
			buf << "] tcp_socket::accept [";
			buf << my_socket.remote_endpoint(ec);
			buf << "]";
			Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
		}
		//----Debug log----------------------------------------------------------------------
	}

	//! close socket
	//! @param[out]		ec is reference error code object
	//! @return 		true is socket close
	//! @return 		false is not open socket
	bool tcp_socket::close(boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::close", __FILE__, __LINE__ );

        rw_scoped_lock scope_lock(close_mutex);

		//----Debug log----------------------------------------------------------------------
		if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){
			if(open_flag){
				boost::system::error_code ec;
				std::stringstream buf;
				buf << "Thread ID[";
				buf << boost::this_thread::get_id();
				buf << "] tcp_socket::close [";
				buf << my_socket.remote_endpoint(ec);
				buf << "]";
				Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
			}
		}
		//----Debug log----------------------------------------------------------------------
		bool bres = false;
		if(open_flag){
			open_flag = false;
			bres = true;
		}
		my_socket.close(ec);

		return bres;
	}

	//! set non blocking mode of the socket
	//! @return			ec is reference error code object
	bool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::set_non_blocking_mode", __FILE__, __LINE__ );

		boost::asio::socket_base::non_blocking_io cmd(true);
		my_socket.io_control(cmd,ec);

		return true;
	}

	//! write socket
	//! @param[in]		buffers is wite data buffer
	//! @param[out]		ec is reference error code object
	//! @return			write data size
	std::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::write_some", __FILE__, __LINE__ );

        rd_scoped_lock scope_lock(close_mutex);
		std::size_t res_size = 0;
		res_size = my_socket.write_some(buffers,ec);
		if(ec){
			if (!open_flag) {
				res_size = 0;
				ec.clear();
			}
		}

		return res_size;
	}

	//! read socket
	//! @param[out]		buffers is read data buffer
	//! @param[out]		ec is reference error code object
	//! @return			read data size
	std::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::read_some", __FILE__, __LINE__ );

        rd_scoped_lock scope_lock(close_mutex);
		std::size_t res_size = 0;
		res_size = my_socket.read_some(buffers,ec);
		if(ec){
			if (!open_flag) {
				res_size = 0;
				ec.clear();
			}
		}

		return res_size;
	}

	//! is open
	//! @return 		true is open
	//! @return 		false is close
	bool tcp_socket::is_open(){
		return open_flag;
	}

}// namespace l7vs

<commit_msg>#336<commit_after>//
//!	@file	tcp_socket.cpp
//!	@brief	tcp session socket class
//
//	copyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD.
//	mail:
//
//	Distributed under the Boost Software License, Version 1.0.(See accompanying
//	file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/thread/thread.hpp>

#include "tcp_socket.h"
#include "logger.h"
#include "utility.h"

namespace l7vs{

	//! construcor
	tcp_socket::tcp_socket(boost::asio::io_service& io):
		my_socket(io),
		open_flag(false){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::tcp_socket", __FILE__, __LINE__ );

	}

	//! destructor
	tcp_socket::~tcp_socket(){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::~tcp_socket", __FILE__, __LINE__ );
	}

	//! get reference control socket
	//! @return			reference control socket
	boost::asio::ip::tcp::socket& tcp_socket::get_socket(){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::get_socket", __FILE__, __LINE__ );
		return my_socket;
	}

	//! connect socket
	//! @param[in]		connect_endpoint is connection endpoint
	//! @param[out]		ec is reference error code object
	//! @return 		true is connect
	//! @return 		false is connect failure
	bool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::connect", __FILE__, __LINE__ );

        rw_scoped_lock scope_lock(close_mutex);

		if(likely(!open_flag)){
			my_socket.connect(connect_endpoint,ec);
			if(unlikely(!ec)){
				open_flag = true;
				//----Debug log----------------------------------------------------------------------
				if (unlikely(LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION))){
					std::stringstream buf;
					buf << "Thread ID[";
					buf << boost::this_thread::get_id();
					buf << "] tcp_socket::connect [";
					buf << connect_endpoint;
					buf << "]";
					Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
				}
				//----Debug log----------------------------------------------------------------------
			}else{
				open_flag = false;
			}
		}
		return open_flag;
	}

	//! accept socket
	void tcp_socket::accept(){
        rw_scoped_lock scope_lock(close_mutex);

		open_flag = true;
		//----Debug log----------------------------------------------------------------------
		if (unlikely(LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION))){
			boost::system::error_code ec;
			std::stringstream buf;
			buf << "Thread ID[";
			buf << boost::this_thread::get_id();
			buf << "] tcp_socket::accept [";
			buf << my_socket.remote_endpoint(ec);
			buf << "]";
			Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
		}
		//----Debug log----------------------------------------------------------------------
	}

	//! close socket
	//! @param[out]		ec is reference error code object
	//! @return 		true is socket close
	//! @return 		false is not open socket
	bool tcp_socket::close(boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::close", __FILE__, __LINE__ );

        rw_scoped_lock scope_lock(close_mutex);

		//----Debug log----------------------------------------------------------------------
		if (unlikely(LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION))){
			if(open_flag){
				boost::system::error_code ec;
				std::stringstream buf;
				buf << "Thread ID[";
				buf << boost::this_thread::get_id();
				buf << "] tcp_socket::close [";
				buf << my_socket.remote_endpoint(ec);
				buf << "]";
				Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );
			}
		}
		//----Debug log----------------------------------------------------------------------
		bool bres = false;
		if(likely(open_flag)){
			open_flag = false;
			bres = true;
		}
		my_socket.close(ec);

		return bres;
	}

	//! set non blocking mode of the socket
	//! @return			ec is reference error code object
	bool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::set_non_blocking_mode", __FILE__, __LINE__ );

		boost::asio::socket_base::non_blocking_io cmd(true);
		my_socket.io_control(cmd,ec);

		return true;
	}

	//! write socket
	//! @param[in]		buffers is wite data buffer
	//! @param[out]		ec is reference error code object
	//! @return			write data size
	std::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::write_some", __FILE__, __LINE__ );

        rd_scoped_lock scope_lock(close_mutex);
		std::size_t res_size = 0;
		res_size = my_socket.write_some(buffers,ec);
		if(unlikely(ec)){
			if (likely(!open_flag)) {
				res_size = 0;
				ec.clear();
			}
		}

		return res_size;
	}

	//! read socket
	//! @param[out]		buffers is read data buffer
	//! @param[out]		ec is reference error code object
	//! @return			read data size
	std::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers,
		boost::system::error_code& ec){
		Logger	logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::read_some", __FILE__, __LINE__ );

        rd_scoped_lock scope_lock(close_mutex);
		std::size_t res_size = 0;
		res_size = my_socket.read_some(buffers,ec);
		if(unlikely(ec)){
			if (likely(!open_flag)) {
				res_size = 0;
				ec.clear();
			}
		}

		return res_size;
	}

	//! is open
	//! @return 		true is open
	//! @return 		false is close
	bool tcp_socket::is_open(){
		return open_flag;
	}

}// namespace l7vs

<|endoftext|>


<commit_before>#include "tds_parser.hpp"
#include "file_handling.hpp"

#include <iostream>

TdsFormat parse_tds(const fs::path tds_file)
{
  TdsFormat tds_format;

  try
  {
    BinaryFile tds(fs::canonical(tds_file).generic_string().c_str());

    const auto signature = read_string<4>(tds());
    if (signature != "FB0A")
      throw std::runtime_error("Wrong signature found! [" + signature + "]");
  }
  catch (const std::runtime_error& e)
  {
    std::cout << "Failed parsing the TDS file: " << e.what() << '\n';
    return tds_format;
  }

  return tds_format;
}
<commit_msg>Continue the implementation of the TDS parsing functions.<commit_after>#include "tds_parser.hpp"
#include "file_handling.hpp"

#include <iostream>

/// @brief Parses out the available information out of the TDS file.
///
/// @param tds_file TDS file to be processed.
///
/// @return Object will all of the data stored.
///
/// @throw std::runtime_error in the event of an parsing error.
TdsFormat parse_tds(const fs::path tds_file)
{
  TdsFormat tds_format;

  try
  {
    BinaryFile tds(fs::canonical(tds_file).generic_string().c_str());

    const auto signature = read_string<4>(tds());
    if (signature != "FB0A")
      throw std::runtime_error("Wrong signature found! [" + signature + "]");

    const auto offset = read_numeric<int32_t>(tds());
    tds().seekg(offset);

    const auto dir_header_size = read_numeric<int16_t>(tds());
    assert(dir_header_size == 16);

    const auto dir_entry_size = read_numeric<int16_t>(tds());
    assert(dir_entry_size == 12);
  }
  catch (const std::runtime_error& e)
  {
    std::cout << "Failed parsing the TDS file: " << e.what() << '\n';
    throw std::runtime_error(e.what());
  }

  return tds_format;
}
<|endoftext|>


<commit_before>#include "test.h"

using nm = transwarp::detail::node_manip;

TEST_CASE("node_clone") {
    auto p1 = std::make_shared<tw::node>();
    auto p2 = std::make_shared<tw::node>();

    tw::node n;
    nm::set_id(n, 42);
    nm::set_level(n, 3);
    nm::set_type(n, tw::task_type::consume_any);
    nm::set_name(n, std::make_optional<std::string>("spacko"));
    nm::set_executor(n, std::make_optional<std::string>("blah"));
    nm::add_parent(n, p1);
    nm::add_parent(n, p2);
    nm::set_priority(n, 13);
    nm::set_custom_data(n, std::make_any<double>(53.8));
    nm::set_canceled(n, true);
    nm::set_avg_idletime_us(n, 1);
    nm::set_avg_waittime_us(n, 2);
    nm::set_avg_runtime_us(n, 3);

    auto cloned = n.clone();
    REQUIRE(42 == cloned->id());
    REQUIRE(3 == cloned->level());
    REQUIRE(tw::task_type::consume_any == cloned->type());
    REQUIRE("spacko" == *cloned->name());
    REQUIRE("blah" == *cloned->executor());
    REQUIRE(0 == cloned->parents().size());
    REQUIRE(13 == cloned->priority());
    REQUIRE(53.8 == std::any_cast<double>(cloned->custom_data()));
    REQUIRE(true == cloned->canceled());
    REQUIRE(1 == cloned->avg_idletime_us());
    REQUIRE(2 == cloned->avg_waittime_us());
    REQUIRE(3 == cloned->avg_runtime_us());
}

TEST_CASE("task_clone") {
    auto p1 = tw::make_task(tw::root, []{ return 42; });
    auto p2 = tw::make_task(tw::consume, [](int x){ return x + 13; }, p1);
    auto t = tw::make_task(tw::consume, [](int x, int y){ return x + y; }, p1, p2);
    t->schedule_all();
    REQUIRE(97 == t->get());
    auto cloned = t->clone();
    cloned->schedule_all();
    REQUIRE(97 == cloned->get());
    REQUIRE(tw::to_string(t->edges()) == tw::to_string(cloned->edges()));
}
<commit_msg>comment out test for mac on travis<commit_after>#include "test.h"

using nm = transwarp::detail::node_manip;

#if !defined(__APPLE__) // any_cast not supported on travis
TEST_CASE("node_clone") {
    auto p1 = std::make_shared<tw::node>();
    auto p2 = std::make_shared<tw::node>();

    tw::node n;
    nm::set_id(n, 42);
    nm::set_level(n, 3);
    nm::set_type(n, tw::task_type::consume_any);
    nm::set_name(n, std::make_optional<std::string>("spacko"));
    nm::set_executor(n, std::make_optional<std::string>("blah"));
    nm::add_parent(n, p1);
    nm::add_parent(n, p2);
    nm::set_priority(n, 13);
    nm::set_custom_data(n, std::make_any<double>(53.8));
    nm::set_canceled(n, true);
    nm::set_avg_idletime_us(n, 1);
    nm::set_avg_waittime_us(n, 2);
    nm::set_avg_runtime_us(n, 3);

    auto cloned = n.clone();
    REQUIRE(42 == cloned->id());
    REQUIRE(3 == cloned->level());
    REQUIRE(tw::task_type::consume_any == cloned->type());
    REQUIRE("spacko" == *cloned->name());
    REQUIRE("blah" == *cloned->executor());
    REQUIRE(0 == cloned->parents().size());
    REQUIRE(13 == cloned->priority());
    REQUIRE(53.8 == std::any_cast<double>(cloned->custom_data()));
    REQUIRE(true == cloned->canceled());
    REQUIRE(1 == cloned->avg_idletime_us());
    REQUIRE(2 == cloned->avg_waittime_us());
    REQUIRE(3 == cloned->avg_runtime_us());
}
#endif

TEST_CASE("task_clone") {
    auto p1 = tw::make_task(tw::root, []{ return 42; });
    auto p2 = tw::make_task(tw::consume, [](int x){ return x + 13; }, p1);
    auto t = tw::make_task(tw::consume, [](int x, int y){ return x + y; }, p1, p2);
    t->schedule_all();
    REQUIRE(97 == t->get());
    auto cloned = t->clone();
    cloned->schedule_all();
    REQUIRE(97 == cloned->get());
    REQUIRE(tw::to_string(t->edges()) == tw::to_string(cloned->edges()));
}
<|endoftext|>


<commit_before>#include "05.hpp"

//////////////
// Includes //
#include <fstream>

#include "../parser.hpp"
#include "../json.hpp"

//////////
// Code //

// Testing the empty object.
bool testEmptyObject(const JValue& emptyObject) {
    if (!emptyObject.isObject())
        return true;

    auto map = emptyObject.jObject();
    int n = 0;

    for (auto it = map.begin(); it != map.end(); it++)
        n++;

    if (n > 0)
        return true;

    return false;
}

// Testing the simple object.
bool testSimpleObject(const JValue& simpleObject) {
    if (!simpleObject.isObject())
        return true;

    std::map<std::string, JValue> map = simpleObject.jObject();

    if (map.count("test") == 0)
        return true;

    if (!map["test"].isBool())
        return true;

    if (map["test"].jBool() != true)
        return true;

    return false;
}

#include <iostream>

// Testing the complex object.
bool testComplexObject(const JValue& complexObject) {
    if (!complexObject.isObject())
        return true;

    auto map = complexObject.jObject();

    // Testing "_id".
    if (!map["_id"].isString() || map["_id"].jString().compare("549d99dee80226183c018588") != 0)
        return true;

    // Testing "index".
    if (!map["index"].isNumber() || (int)map["index"].jNumber() != 0)
        return true;

    // Testing "guid"
    if (!map["guid"].isString() || map["guid"].jString().compare("1db598d0-3333-4aea-aa5e-4be986236e56") != 0)
        return true;

    // Testing "isActive"
    if (!map["isActive"].isBool() || map["isActive"].jBool() != false)
        return true;

    // Testing "balance"
    if (!map["balance"].isString() || map["balance"].jString().compare("$2,983.05") != 0)
        return true;

    // Testing "picture"
    if (!map["picture"].isString() || map["picture"].jString().compare("http://placehold.it/32x32") != 0)
        return true;

    // Testing "age"
    if (!map["age"].isNumber() || (int)map["age"].jNumber() != 34)
        return true;

    // Testing "eyeColor"
    if (!map["eyeColor"].isString() || map["eyeColor"].jString().compare("brown") != 0)
        return true;

    // Testing "name"
    if (!map["name"].isString() || map["name"].jString().compare("Hale Bridges") != 0)
        return true;

    // Testing "gender"
    if (!map["gender"].isString() || map["gender"].jString().compare("male") != 0)
        return true;

    // Testing "company"
    if (!map["company"].isString() || map["company"].jString().compare("ENTROPIX") != 0)
        return true;

    // Testing "email"
    if (!map["email"].isString() || map["email"].jString().compare("halebridges@entropix.com") != 0)
        return true;

    // Testing "phone"
    if (!map["phone"].isString() || map["phone"].jString().compare("+1 (879) 419-2839") != 0)
        return true;

    // Testing "address"
    if (!map["address"].isString() || map["address"].jString().compare("256 Chester Court, Bergoo, Massachusetts, 3694") != 0)
        return true;

    // Testing "about"
    if (!map["about"].isString() || map["about"].jString().compare("Fugiat cupidatat adipisicing sit laborum reprehenderit occaecat laboris eiusmod et. Cupidatat dolore occaecat eu voluptate laborum non esse et labore laboris elit dolor adipisicing. Dolore ex eu et id Lorem. Irure ullamco enim nisi et excepteur ad elit ut sint magna magna magna dolore. Amet nisi et aliqua adipisicing duis et proident do. Velit sit elit tempor eu. Eu anim aliquip laboris nisi aliqua irure proident do.\r\n") != 0)
        return true;

    // Testing "registered"
    if (!map["registered"].isString() || map["registered"].jString().compare("2014-12-23T05:02:09 +05:00") != 0)
        return true;

    // Testing "latitude"
    if (!map["latitude"].isNumber() || map["latitude"].jNumber() != 78.328387)
        return true;

    // Testing "longitude"
    if (!map["longitude"].isNumber() || map["longitude"].jNumber() != -81.043504)
        return true;

    // Testing "tags"
    if (map["tags"].isArray()) {
        auto tags = map["tags"].jArray();

        for (auto it = tags.begin(); it != tags.end(); it++)
            std::cout << it->jString() << " ";
        std::cout << std::endl;

        if (!tags[0].isString() || tags[0].jString().compare("voluptate") != 0)
            return true;
        if (!tags[1].isString() || tags[1].jString().compare("incididunt") != 0)
            return true;
        if (!tags[2].isString() || tags[2].jString().compare("consectetur") != 0)
            return true;
        if (!tags[3].isString() || tags[3].jString().compare("consectetur") != 0)
            return true;
        if (!tags[4].isString() || tags[4].jString().compare("voluptate") != 0)
            return true;
        if (!tags[5].isString() || tags[5].jString().compare("dolore") != 0)
            return true;
        if (!tags[6].isString() || tags[6].jString().compare("in") != 0)
            return true;
    } else
        return true;

    return false;
}

// Attempting to test parseJSON for 'null' values.
int runTest05() {
    JValue emptyObject = parseJSON("{ }");
    JValue simpleObject = parseJSON("{ \"test\": true }");

    // Loading a piece of test JSON from a file.
    std::ifstream reader("data/complex.json");
    if (!reader.good())
        return 2;
    JValue complexObject = parseJSON(reader);

    if (testEmptyObject(emptyObject))
        return 1;
    if (testSimpleObject(simpleObject))
        return 1;
    if (testComplexObject(complexObject))
        return 1;

    return 0;
}
<commit_msg>Finally finished writing the complex JSON test. It works.<commit_after>#include "05.hpp"

//////////////
// Includes //
#include <fstream>

#include "../parser.hpp"
#include "../json.hpp"

//////////
// Code //

// Testing the empty object.
bool testEmptyObject(const JValue& emptyObject) {
    if (!emptyObject.isObject())
        return true;

    auto map = emptyObject.jObject();
    int n = 0;

    for (auto it = map.begin(); it != map.end(); it++)
        n++;

    if (n > 0)
        return true;

    return false;
}

// Testing the simple object.
bool testSimpleObject(const JValue& simpleObject) {
    if (!simpleObject.isObject())
        return true;

    std::map<std::string, JValue> map = simpleObject.jObject();

    if (map.count("test") == 0)
        return true;

    if (!map["test"].isBool())
        return true;

    if (map["test"].jBool() != true)
        return true;

    return false;
}

#include <iostream>

// Testing the complex object.
bool testComplexObject(const JValue& complexObject) {
    if (!complexObject.isObject())
        return true;

    auto map = complexObject.jObject();

    // Testing "_id".
    if (!map["_id"].isString() || map["_id"].jString().compare("549d99dee80226183c018588") != 0)
        return true;

    // Testing "index".
    if (!map["index"].isNumber() || (int)map["index"].jNumber() != 0)
        return true;

    // Testing "guid"
    if (!map["guid"].isString() || map["guid"].jString().compare("1db598d0-3333-4aea-aa5e-4be986236e56") != 0)
        return true;

    // Testing "isActive"
    if (!map["isActive"].isBool() || map["isActive"].jBool() != false)
        return true;

    // Testing "balance"
    if (!map["balance"].isString() || map["balance"].jString().compare("$2,983.05") != 0)
        return true;

    // Testing "picture"
    if (!map["picture"].isString() || map["picture"].jString().compare("http://placehold.it/32x32") != 0)
        return true;

    // Testing "age"
    if (!map["age"].isNumber() || (int)map["age"].jNumber() != 34)
        return true;

    // Testing "eyeColor"
    if (!map["eyeColor"].isString() || map["eyeColor"].jString().compare("brown") != 0)
        return true;

    // Testing "name"
    if (!map["name"].isString() || map["name"].jString().compare("Hale Bridges") != 0)
        return true;

    // Testing "gender"
    if (!map["gender"].isString() || map["gender"].jString().compare("male") != 0)
        return true;

    // Testing "company"
    if (!map["company"].isString() || map["company"].jString().compare("ENTROPIX") != 0)
        return true;

    // Testing "email"
    if (!map["email"].isString() || map["email"].jString().compare("halebridges@entropix.com") != 0)
        return true;

    // Testing "phone"
    if (!map["phone"].isString() || map["phone"].jString().compare("+1 (879) 419-2839") != 0)
        return true;

    // Testing "address"
    if (!map["address"].isString() || map["address"].jString().compare("256 Chester Court, Bergoo, Massachusetts, 3694") != 0)
        return true;

    // Testing "about"
    if (!map["about"].isString() || map["about"].jString().compare("Fugiat cupidatat adipisicing sit laborum reprehenderit occaecat laboris eiusmod et. Cupidatat dolore occaecat eu voluptate laborum non esse et labore laboris elit dolor adipisicing. Dolore ex eu et id Lorem. Irure ullamco enim nisi et excepteur ad elit ut sint magna magna magna dolore. Amet nisi et aliqua adipisicing duis et proident do. Velit sit elit tempor eu. Eu anim aliquip laboris nisi aliqua irure proident do.\r\n") != 0)
        return true;

    // Testing "registered"
    if (!map["registered"].isString() || map["registered"].jString().compare("2014-12-23T05:02:09 +05:00") != 0)
        return true;

    // Testing "latitude"
    if (!map["latitude"].isNumber() || map["latitude"].jNumber() != 78.328387)
        return true;

    // Testing "longitude"
    if (!map["longitude"].isNumber() || map["longitude"].jNumber() != -81.043504)
        return true;

    // Testing "tags"
    if (map["tags"].isArray()) {
        auto tags = map["tags"].jArray();

        for (auto it = tags.begin(); it != tags.end(); it++)
            std::cout << it->jString() << " ";
        std::cout << std::endl;

        if (!tags[0].isString() || tags[0].jString().compare("voluptate") != 0)
            return true;
        if (!tags[1].isString() || tags[1].jString().compare("incididunt") != 0)
            return true;
        if (!tags[2].isString() || tags[2].jString().compare("consectetur") != 0)
            return true;
        if (!tags[3].isString() || tags[3].jString().compare("consectetur") != 0)
            return true;
        if (!tags[4].isString() || tags[4].jString().compare("voluptate") != 0)
            return true;
        if (!tags[5].isString() || tags[5].jString().compare("dolore") != 0)
            return true;
        if (!tags[6].isString() || tags[6].jString().compare("in") != 0)
            return true;
    } else
        return true;

    if (map["friends"].isArray()) {
        auto friends = map["friends"].jArray();
        for (auto it = friends.begin(); it != friends.end(); it++)
            if (!it->isObject())
                return true;

        for (int i = 0; i < friends.size(); i++) {
            if (!friends[i].isObject())
                return true;

            auto smap = friends[i].jObject();
            std::string name;

            switch (i) {
            case 0:
                name = "Connie Douglas";
                break;
            case 1:
                name = "Charlotte Collins";
                break;
            case 2:
                name = "Esperanza Emerson";
                break;
            }

            if (!smap["id"].isNumber() || (int)smap["id"].jNumber() != i)
                return true;
            if (!smap["name"].isString() || smap["name"].jString().compare(name) != 0)
                return true;
        }
    } else
        return true;

    if (!map["greeting"].isString() || map["greeting"].jString().compare("Hello, Hale Bridges! You have 6 unread messages.") != 0)
        return true;

    if (!map["favoriteFruit"].isString() || map["favoriteFruit"].jString().compare("strawberry") != 0)
        return true;

    return false;
}

// Attempting to test parseJSON for 'null' values.
int runTest05() {
    JValue emptyObject = parseJSON("{ }");
    JValue simpleObject = parseJSON("{ \"test\": true }");

    // Loading a piece of test JSON from a file.
    std::ifstream reader("data/complex.json");
    if (!reader.good())
        return 2;
    JValue complexObject = parseJSON(reader);
    reader.close();

    if (testEmptyObject(emptyObject))
        return 1;
    if (testSimpleObject(simpleObject))
        return 1;
    if (testComplexObject(complexObject))
        return 1;

    return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "File.h"

#include "medialibrary/filesystem/Errors.h"

#include <memory>
#include <cstdio>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

namespace medialibrary
{

namespace utils
{

namespace fs
{

bool copy( const std::string& from, const std::string& to )
{
#ifdef HAVE_LINK
    if ( link( from.c_str(), to.c_str() ) == 0 )
        return true;
    if ( errno == EEXIST )
    {
        remove( to );
        if ( link( from.c_str(), to.c_str() ) == 0 )
            return true;
    }
    switch ( errno )
    {
        case EXDEV: // No cross device link, too bad then, let's copy
        case EPERM: // In case the user isn't allowed to create links, or the
                    // filesystem doesn't support it, let's try with a deep copy.
            break;
        default:
            return false;
    }
#endif
    std::unique_ptr<FILE, decltype(&fclose)> input{
        fopen( from.c_str(), "rb" ), &fclose
    };
    std::unique_ptr<FILE, decltype(&fclose)> output{
        fopen( to.c_str(), "wb" ), &fclose
    };
    if ( input == nullptr || output == nullptr )
        return false;
    unsigned char buff[4096];

    do
    {
        auto nbRead = fread( buff, 1, 4096, input.get() );
        if ( nbRead == 0 )
        {
            if ( ferror( input.get() ) )
                return false;
            break;
        }
        if ( fwrite( buff, 1, nbRead, output.get() ) == 0 )
            return false;
    } while ( feof( input.get() ) == 0 );
    return true;
}

bool remove( const std::string& path )
{
    return unlink( path.c_str() ) == 0;
}

uint64_t fileSize( const std::string& path )
{
    struct stat s;
    if ( stat( path.c_str(), &s ) != 0 )
    {
        throw ::medialibrary::fs::errors::Exception{ std::string{
            "Failed to compute file size for " + path } };
    }
    return s.st_size;
}

}

}

}
<commit_msg>utils: File: Use the C++ header variant<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "File.h"

#include "medialibrary/filesystem/Errors.h"

#include <memory>
#include <cstdio>
#include <unistd.h>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>

namespace medialibrary
{

namespace utils
{

namespace fs
{

bool copy( const std::string& from, const std::string& to )
{
#ifdef HAVE_LINK
    if ( link( from.c_str(), to.c_str() ) == 0 )
        return true;
    if ( errno == EEXIST )
    {
        remove( to );
        if ( link( from.c_str(), to.c_str() ) == 0 )
            return true;
    }
    switch ( errno )
    {
        case EXDEV: // No cross device link, too bad then, let's copy
        case EPERM: // In case the user isn't allowed to create links, or the
                    // filesystem doesn't support it, let's try with a deep copy.
            break;
        default:
            return false;
    }
#endif
    std::unique_ptr<FILE, decltype(&fclose)> input{
        fopen( from.c_str(), "rb" ), &fclose
    };
    std::unique_ptr<FILE, decltype(&fclose)> output{
        fopen( to.c_str(), "wb" ), &fclose
    };
    if ( input == nullptr || output == nullptr )
        return false;
    unsigned char buff[4096];

    do
    {
        auto nbRead = fread( buff, 1, 4096, input.get() );
        if ( nbRead == 0 )
        {
            if ( ferror( input.get() ) )
                return false;
            break;
        }
        if ( fwrite( buff, 1, nbRead, output.get() ) == 0 )
            return false;
    } while ( feof( input.get() ) == 0 );
    return true;
}

bool remove( const std::string& path )
{
    return unlink( path.c_str() ) == 0;
}

uint64_t fileSize( const std::string& path )
{
    struct stat s;
    if ( stat( path.c_str(), &s ) != 0 )
    {
        throw ::medialibrary::fs::errors::Exception{ std::string{
            "Failed to compute file size for " + path } };
    }
    return s.st_size;
}

}

}

}
<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vector>

#include <vw/Core/Log.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Settings.h>

// C Standard Library headers ( for stat(2) and getpwuid() )
#include <sys/types.h>
#include <sys/stat.h>
#include <ctime>

#include <vw/config.h>

#ifdef VW_HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef VW_HAVE_PWD_H
#include <pwd.h>
#endif

#ifdef WIN32
#define stat _stat
typedef struct _stat struct_stat;
#else
typedef struct stat struct_stat;
#endif

inline std::string
current_posix_time_string()
{
  char time_string[2048];
  time_t t = time(0);
  struct tm* time_struct = localtime(&t);
  strftime(time_string, 2048, "%F %T", time_struct);
  return std::string(time_string);
}

// ---------------------------------------------------
// Create a single instance of the SystemLog
// ---------------------------------------------------
namespace {
  static vw::null_ostream g_null_ostream;
  vw::RunOnce system_log_once = VW_RUNONCE_INIT;
  boost::shared_ptr<vw::Log> system_log_ptr;
  void init_system_log() {
    system_log_ptr = boost::shared_ptr<vw::Log>(new vw::Log());
  }
}

// ---------------------------------------------------
// Basic stream support
// ---------------------------------------------------
std::ostream& vw::vw_out( int log_level, std::string log_namespace ) {
  return vw_log()(log_level, log_namespace);
}

void vw::set_debug_level( int log_level ) {
  vw_log().console_log().rule_set().add_rule(log_level, "console");
}

void vw::set_output_stream( std::ostream& stream ) {
  vw_log().set_console_stream(stream);
}

// ---------------------------------------------------
// LogInstance Methods
// ---------------------------------------------------
vw::LogInstance::LogInstance(std::string log_filename, bool prepend_infostamp) : m_prepend_infostamp(prepend_infostamp) {
  // Open file and place the insertion pointer at the end of the file (ios_base::ate)
  m_log_ostream_ptr = new std::ofstream(log_filename.c_str(), std::ios::app);
  if (! static_cast<std::ofstream*>(m_log_ostream_ptr)->is_open())
    vw_throw(IOErr() << "Could not open log file " << log_filename << " for writing.");

  *m_log_ostream_ptr << "\n\n" << "Vision Workbench log started at " << current_posix_time_string() << ".\n\n";

  m_log_stream.set_stream(*m_log_ostream_ptr);
}

vw::LogInstance::LogInstance(std::ostream& log_ostream, bool prepend_infostamp) : m_log_stream(log_ostream),
                                                                                m_log_ostream_ptr(NULL),
                                                                                m_prepend_infostamp(prepend_infostamp) {}

std::ostream& vw::LogInstance::operator() (int log_level, std::string log_namespace) {
  if (m_rule_set(log_level, log_namespace)) {
    if (m_prepend_infostamp)
      m_log_stream << current_posix_time_string() << " {" << Thread::id() << "} [ " << log_namespace << " ] : ";
    switch (log_level) {
      case ErrorMessage:   m_log_stream << "Error: ";   break;
      case WarningMessage: m_log_stream << "Warning: "; break;
      default: break;
    }
    return m_log_stream;
  } else {
    return g_null_ostream;
  }
}

std::ostream& vw::Log::operator() (int log_level, std::string log_namespace) {
  // First, check to see if the rc file has been updated.
  // Reload the rulesets if it has.
  vw_settings().reload_config();

  {
    Mutex::Lock multi_ostreams_lock(m_multi_ostreams_mutex);

    // Check to see if we have an ostream defined yet for this thread.
    if(m_multi_ostreams.find( Thread::id() ) == m_multi_ostreams.end())
      m_multi_ostreams[ Thread::id() ] = boost::shared_ptr<multi_ostream>(new multi_ostream);

    // Reset and add the console log output...
    m_multi_ostreams[ Thread::id() ]->clear();
    m_multi_ostreams[ Thread::id() ]->add(m_console_log->operator()(log_level, log_namespace));

    // ... and the rest of the active log streams.
    std::vector<boost::shared_ptr<LogInstance> >::iterator iter = m_logs.begin();
    for (;iter != m_logs.end(); ++iter)
      m_multi_ostreams[ Thread::id() ]->add((*iter)->operator()(log_level,log_namespace));

    return *m_multi_ostreams[ Thread::id() ];
  }
}

vw::Log& vw::vw_log() {
  system_log_once.run( init_system_log );
  return *system_log_ptr;
}
<commit_msg>speed up vw_log() slightly<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vector>

#include <vw/Core/Log.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Settings.h>

// C Standard Library headers ( for stat(2) and getpwuid() )
#include <sys/types.h>
#include <sys/stat.h>
#include <ctime>

#include <vw/config.h>

#ifdef VW_HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef VW_HAVE_PWD_H
#include <pwd.h>
#endif

#ifdef WIN32
#define stat _stat
typedef struct _stat struct_stat;
#else
typedef struct stat struct_stat;
#endif

inline std::string
current_posix_time_string()
{
  char time_string[2048];
  time_t t = time(0);
  struct tm* time_struct = localtime(&t);
  strftime(time_string, 2048, "%F %T", time_struct);
  return std::string(time_string);
}

// ---------------------------------------------------
// Create a single instance of the SystemLog
// ---------------------------------------------------
namespace {
  static vw::null_ostream g_null_ostream;
  vw::RunOnce system_log_once = VW_RUNONCE_INIT;
  boost::shared_ptr<vw::Log> system_log_ptr;
  void init_system_log() {
    system_log_ptr = boost::shared_ptr<vw::Log>(new vw::Log());
  }
}

// ---------------------------------------------------
// Basic stream support
// ---------------------------------------------------
std::ostream& vw::vw_out( int log_level, std::string log_namespace ) {
  return vw_log()(log_level, log_namespace);
}

void vw::set_debug_level( int log_level ) {
  vw_log().console_log().rule_set().add_rule(log_level, "console");
}

void vw::set_output_stream( std::ostream& stream ) {
  vw_log().set_console_stream(stream);
}

// ---------------------------------------------------
// LogInstance Methods
// ---------------------------------------------------
vw::LogInstance::LogInstance(std::string log_filename, bool prepend_infostamp) : m_prepend_infostamp(prepend_infostamp) {
  // Open file and place the insertion pointer at the end of the file (ios_base::ate)
  m_log_ostream_ptr = new std::ofstream(log_filename.c_str(), std::ios::app);
  if (! static_cast<std::ofstream*>(m_log_ostream_ptr)->is_open())
    vw_throw(IOErr() << "Could not open log file " << log_filename << " for writing.");

  *m_log_ostream_ptr << "\n\n" << "Vision Workbench log started at " << current_posix_time_string() << ".\n\n";

  m_log_stream.set_stream(*m_log_ostream_ptr);
}

vw::LogInstance::LogInstance(std::ostream& log_ostream, bool prepend_infostamp) : m_log_stream(log_ostream),
                                                                                m_log_ostream_ptr(NULL),
                                                                                m_prepend_infostamp(prepend_infostamp) {}

std::ostream& vw::LogInstance::operator() (int log_level, std::string log_namespace) {
  if (m_rule_set(log_level, log_namespace)) {
    if (m_prepend_infostamp)
      m_log_stream << current_posix_time_string() << " {" << Thread::id() << "} [ " << log_namespace << " ] : ";
    switch (log_level) {
      case ErrorMessage:   m_log_stream << "Error: ";   break;
      case WarningMessage: m_log_stream << "Warning: "; break;
      default: break;
    }
    return m_log_stream;
  } else {
    return g_null_ostream;
  }
}

std::ostream& vw::Log::operator() (int log_level, std::string log_namespace) {
  // First, check to see if the rc file has been updated.
  // Reload the rulesets if it has.
  vw_settings().reload_config();

  {
    Mutex::Lock multi_ostreams_lock(m_multi_ostreams_mutex);

    // Check to see if we have an ostream defined yet for this thread.
    if(m_multi_ostreams.find( Thread::id() ) == m_multi_ostreams.end())
      m_multi_ostreams[ Thread::id() ] = boost::shared_ptr<multi_ostream>(new multi_ostream);

    boost::shared_ptr<multi_ostream>& stream = m_multi_ostreams[ Thread::id() ];

    // Reset and add the console log output...
    stream->clear();
    stream->add(m_console_log->operator()(log_level, log_namespace));

    // ... and the rest of the active log streams.
    std::vector<boost::shared_ptr<LogInstance> >::iterator iter = m_logs.begin();
    for (;iter != m_logs.end(); ++iter)
      stream->add((*iter)->operator()(log_level,log_namespace));

    return *stream;
  }
}

vw::Log& vw::vw_log() {
  system_log_once.run( init_system_log );
  return *system_log_ptr;
}
<|endoftext|>