<commit_before>// Copyright (c) 2012 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 <fcntl.h>
#include <unistd.h>

#include "chromeos/dbus/debug_daemon_client.h"

#include "base/bind.h"
#include "base/callback.h"
#include "base/chromeos/chromeos_version.h"
#include "base/eintr_wrapper.h"
#include "base/memory/ref_counted_memory.h"
#include "base/platform_file.h"
#include "base/string_util.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace {

// Used in DebugDaemonClient::EmptySystemStopTracingCallback().
void EmptyStopSystemTracingCallbackBody(
  const scoped_refptr<base::RefCountedString>& unused_result) {
}

// Simple class to encapsulate collecting data from a pipe into a
// string.  To use, instantiate the class, start i/o, and then delete
// the instance on callback.  The data should be retrieved before
// delete and extracted or copied.
//
// TODO(sleffler) move data collection to a sub-class so this
// can be reused to process data as it is received
class PipeReader {
 public:
  typedef base::Callback<void(void)>IOCompleteCallback;

  explicit PipeReader(IOCompleteCallback callback)
      : data_stream_(NULL),
        io_buffer_(new net::IOBufferWithSize(4096)),
        weak_ptr_factory_(this),
        callback_(callback) {
    pipe_fd_[0] = pipe_fd_[1] = -1;
  }

  virtual ~PipeReader() {
    if (pipe_fd_[0] != -1)
      if (HANDLE_EINTR(close(pipe_fd_[0])) < 0)
        PLOG(ERROR) << "close[0]";
    if (pipe_fd_[1] != -1)
      if (HANDLE_EINTR(close(pipe_fd_[1])) < 0)
        PLOG(ERROR) << "close[1]";
  }

  // Returns descriptor for the writeable side of the pipe.
  int GetWriteFD() { return pipe_fd_[1]; }

  // Closes writeable descriptor; normally used in parent process after fork.
  void CloseWriteFD() {
    if (pipe_fd_[1] != -1) {
      if (HANDLE_EINTR(close(pipe_fd_[1])) < 0)
        PLOG(ERROR) << "close";
      pipe_fd_[1] = -1;
    }
  }

  // Returns collected data.
  std::string* data() { return &data_; }

  // Starts data collection.  Returns true if stream was setup correctly.
  // On success data will automatically be accumulated into a string that
  // can be retrieved with PipeReader::data().  To shutdown collection delete
  // the instance and/or use PipeReader::OnDataReady(-1).
  bool StartIO() {
    // Use a pipe to collect data
    const int status = HANDLE_EINTR(pipe(pipe_fd_));
    if (status < 0) {
      PLOG(ERROR) << "pipe";
      return false;
    }
    base::PlatformFile data_file_ = pipe_fd_[0];  // read side
    data_stream_.reset(new net::FileStream(data_file_,
        base::PLATFORM_FILE_READ | base::PLATFORM_FILE_ASYNC,
        NULL));

    // Post an initial async read to setup data collection
    int rv = data_stream_->Read(io_buffer_.get(), io_buffer_->size(),
        base::Bind(&PipeReader::OnDataReady, weak_ptr_factory_.GetWeakPtr()));
    if (rv != net::ERR_IO_PENDING) {
      LOG(ERROR) << "Unable to post initial read";
      return false;
    }
    return true;
  }

  // Called when pipe data are available.  Can also be used to shutdown
  // data collection by passing -1 for |byte_count|.
  void OnDataReady(int byte_count) {
    DVLOG(1) << "OnDataReady byte_count " << byte_count;
    if (byte_count <= 0) {
      callback_.Run();  // signal creator to take data and delete us
      return;
    }
    data_.append(io_buffer_->data(), byte_count);

    // Post another read
    int rv = data_stream_->Read(io_buffer_.get(), io_buffer_->size(),
        base::Bind(&PipeReader::OnDataReady, weak_ptr_factory_.GetWeakPtr()));
    if (rv != net::ERR_IO_PENDING) {
      LOG(ERROR) << "Unable to post another read";
      // TODO(sleffler) do something more intelligent?
    }
  }

 private:
  friend class base::RefCounted<PipeReader>;

  int pipe_fd_[2];
  scoped_ptr<net::FileStream> data_stream_;
  scoped_refptr<net::IOBufferWithSize> io_buffer_;
  base::WeakPtrFactory<PipeReader> weak_ptr_factory_;
  std::string data_;
  IOCompleteCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(PipeReader);
};

}  // namespace

namespace chromeos {

// The DebugDaemonClient implementation used in production.
class DebugDaemonClientImpl : public DebugDaemonClient {
 public:
  explicit DebugDaemonClientImpl(dbus::Bus* bus)
      : debugdaemon_proxy_(NULL),
        weak_ptr_factory_(this),
        pipe_reader_(NULL) {
    debugdaemon_proxy_ = bus->GetObjectProxy(
        debugd::kDebugdServiceName,
        dbus::ObjectPath(debugd::kDebugdServicePath));
  }

  virtual ~DebugDaemonClientImpl() {}

  // DebugDaemonClient override.
  virtual void GetDebugLogs(base::PlatformFile file,
                            const GetDebugLogsCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kGetDebugLogs);
    dbus::MessageWriter writer(&method_call);
    dbus::FileDescriptor fd(file);  // explicit temp for C++ 98
    writer.AppendFileDescriptor(fd);

    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnGetDebugLogs,
                   weak_ptr_factory_.GetWeakPtr(),
                   callback));
  }

  virtual void SetDebugMode(const std::string& subsystem,
                            const SetDebugModeCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(debugd::kDebugdInterface,
                                 debugd::kSetDebugMode);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(subsystem);
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnSetDebugMode,
                   weak_ptr_factory_.GetWeakPtr(),
                   callback));
  }

  virtual void StartSystemTracing() OVERRIDE {
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kSystraceStart);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString("all"); // TODO(sleffler) parameterize category list

    DVLOG(1) << "Requesting a systrace start";
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnStartSystemTracing,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual bool RequestStopSystemTracing(const StopSystemTracingCallback&
      callback) OVERRIDE {
    if (pipe_reader_ != NULL) {
      LOG(ERROR) << "Busy doing StopSystemTracing";
      return false;
    }

    pipe_reader_.reset(new PipeReader(
        base::Bind(&DebugDaemonClientImpl::OnIOComplete,
                   weak_ptr_factory_.GetWeakPtr())));
    int write_fd = -1;
    if (!pipe_reader_->StartIO()) {
      LOG(ERROR) << "Cannot create pipe reader";
      // NB: continue anyway to shutdown tracing; toss trace data
      write_fd = HANDLE_EINTR(open("/dev/null", O_WRONLY));
      // TODO(sleffler) if this fails AppendFileDescriptor will abort
    } else {
      write_fd = pipe_reader_->GetWriteFD();
    }

    DCHECK(callback.is_null());
    callback_ = callback;

    // Issue the dbus request to stop system tracing
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kSystraceStop);
    dbus::MessageWriter writer(&method_call);
    dbus::FileDescriptor temp(write_fd);  // NB: explicit temp for C++98
    writer.AppendFileDescriptor(temp);

    DVLOG(1) << "Requesting a systrace stop";
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnRequestStopSystemTracing,
                   weak_ptr_factory_.GetWeakPtr()));

    pipe_reader_->CloseWriteFD();  // close our copy of fd after send

    return true;
  }

 private:
  // Called when a response for GetDebugLogs() is received.
  void OnGetDebugLogs(const GetDebugLogsCallback& callback,
                      dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to get debug logs";
      callback.Run(false);
      return;
    }
    callback.Run(true);
  }

  // Called when a response for SetDebugMode() is received.
  void OnSetDebugMode(const SetDebugModeCallback& callback,
                      dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to change debug mode";
      callback.Run(false);
    } else {
      callback.Run(true);
    }
  }

  // Called when a response for StartSystemTracing() is received.
  void OnStartSystemTracing(dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to request systrace start";
      return;
    }
  }

  // Called when a response for RequestStopSystemTracing() is received.
  void OnRequestStopSystemTracing(dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to request systrace stop";
      pipe_reader_->OnDataReady(-1); // terminate data stream
    }
    // NB: requester is signaled when i/o completes
  }

  // Called when pipe i/o completes; pass data on and delete the instance.
  void OnIOComplete() {
    callback_.Run(base::RefCountedString::TakeString(pipe_reader_->data()));
    pipe_reader_.reset();
  }

  dbus::ObjectProxy* debugdaemon_proxy_;
  base::WeakPtrFactory<DebugDaemonClientImpl> weak_ptr_factory_;
  scoped_ptr<PipeReader> pipe_reader_;
  StopSystemTracingCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(DebugDaemonClientImpl);
};

// The DebugDaemonClient implementation used on Linux desktop,
// which does nothing.
class DebugDaemonClientStubImpl : public DebugDaemonClient {
  // DebugDaemonClient overrides.
  virtual void GetDebugLogs(base::PlatformFile file,
                            const GetDebugLogsCallback& callback) OVERRIDE {
    callback.Run(false);
  }
  virtual void SetDebugMode(const std::string& subsystem,
                            const SetDebugModeCallback& callback) OVERRIDE {
    callback.Run(false);
  }
  virtual void StartSystemTracing() OVERRIDE {}
  virtual bool RequestStopSystemTracing(const StopSystemTracingCallback&
      callback) OVERRIDE {
    std::string no_data;
    callback.Run(base::RefCountedString::TakeString(&no_data));
    return true;
  }
};

DebugDaemonClient::DebugDaemonClient() {
}

DebugDaemonClient::~DebugDaemonClient() {
}

// static
DebugDaemonClient::StopSystemTracingCallback
DebugDaemonClient::EmptyStopSystemTracingCallback() {
  return base::Bind(&EmptyStopSystemTracingCallbackBody);
}

// static
DebugDaemonClient* DebugDaemonClient::Create(DBusClientImplementationType type,
                                   dbus::Bus* bus) {
  if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
    return new DebugDaemonClientImpl(bus);
  DCHECK_EQ(STUB_DBUS_CLIENT_IMPLEMENTATION, type);
  return new DebugDaemonClientStubImpl();
}

}  // namespace chromeos
<commit_msg>Purge bogus debug assert.<commit_after>// Copyright (c) 2012 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 <fcntl.h>
#include <unistd.h>

#include "chromeos/dbus/debug_daemon_client.h"

#include "base/bind.h"
#include "base/callback.h"
#include "base/chromeos/chromeos_version.h"
#include "base/eintr_wrapper.h"
#include "base/memory/ref_counted_memory.h"
#include "base/platform_file.h"
#include "base/string_util.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "net/base/file_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace {

// Used in DebugDaemonClient::EmptySystemStopTracingCallback().
void EmptyStopSystemTracingCallbackBody(
  const scoped_refptr<base::RefCountedString>& unused_result) {
}

// Simple class to encapsulate collecting data from a pipe into a
// string.  To use, instantiate the class, start i/o, and then delete
// the instance on callback.  The data should be retrieved before
// delete and extracted or copied.
//
// TODO(sleffler) move data collection to a sub-class so this
// can be reused to process data as it is received
class PipeReader {
 public:
  typedef base::Callback<void(void)>IOCompleteCallback;

  explicit PipeReader(IOCompleteCallback callback)
      : data_stream_(NULL),
        io_buffer_(new net::IOBufferWithSize(4096)),
        weak_ptr_factory_(this),
        callback_(callback) {
    pipe_fd_[0] = pipe_fd_[1] = -1;
  }

  virtual ~PipeReader() {
    if (pipe_fd_[0] != -1)
      if (HANDLE_EINTR(close(pipe_fd_[0])) < 0)
        PLOG(ERROR) << "close[0]";
    if (pipe_fd_[1] != -1)
      if (HANDLE_EINTR(close(pipe_fd_[1])) < 0)
        PLOG(ERROR) << "close[1]";
  }

  // Returns descriptor for the writeable side of the pipe.
  int GetWriteFD() { return pipe_fd_[1]; }

  // Closes writeable descriptor; normally used in parent process after fork.
  void CloseWriteFD() {
    if (pipe_fd_[1] != -1) {
      if (HANDLE_EINTR(close(pipe_fd_[1])) < 0)
        PLOG(ERROR) << "close";
      pipe_fd_[1] = -1;
    }
  }

  // Returns collected data.
  std::string* data() { return &data_; }

  // Starts data collection.  Returns true if stream was setup correctly.
  // On success data will automatically be accumulated into a string that
  // can be retrieved with PipeReader::data().  To shutdown collection delete
  // the instance and/or use PipeReader::OnDataReady(-1).
  bool StartIO() {
    // Use a pipe to collect data
    const int status = HANDLE_EINTR(pipe(pipe_fd_));
    if (status < 0) {
      PLOG(ERROR) << "pipe";
      return false;
    }
    base::PlatformFile data_file_ = pipe_fd_[0];  // read side
    data_stream_.reset(new net::FileStream(data_file_,
        base::PLATFORM_FILE_READ | base::PLATFORM_FILE_ASYNC,
        NULL));

    // Post an initial async read to setup data collection
    int rv = data_stream_->Read(io_buffer_.get(), io_buffer_->size(),
        base::Bind(&PipeReader::OnDataReady, weak_ptr_factory_.GetWeakPtr()));
    if (rv != net::ERR_IO_PENDING) {
      LOG(ERROR) << "Unable to post initial read";
      return false;
    }
    return true;
  }

  // Called when pipe data are available.  Can also be used to shutdown
  // data collection by passing -1 for |byte_count|.
  void OnDataReady(int byte_count) {
    DVLOG(1) << "OnDataReady byte_count " << byte_count;
    if (byte_count <= 0) {
      callback_.Run();  // signal creator to take data and delete us
      return;
    }
    data_.append(io_buffer_->data(), byte_count);

    // Post another read
    int rv = data_stream_->Read(io_buffer_.get(), io_buffer_->size(),
        base::Bind(&PipeReader::OnDataReady, weak_ptr_factory_.GetWeakPtr()));
    if (rv != net::ERR_IO_PENDING) {
      LOG(ERROR) << "Unable to post another read";
      // TODO(sleffler) do something more intelligent?
    }
  }

 private:
  friend class base::RefCounted<PipeReader>;

  int pipe_fd_[2];
  scoped_ptr<net::FileStream> data_stream_;
  scoped_refptr<net::IOBufferWithSize> io_buffer_;
  base::WeakPtrFactory<PipeReader> weak_ptr_factory_;
  std::string data_;
  IOCompleteCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(PipeReader);
};

}  // namespace

namespace chromeos {

// The DebugDaemonClient implementation used in production.
class DebugDaemonClientImpl : public DebugDaemonClient {
 public:
  explicit DebugDaemonClientImpl(dbus::Bus* bus)
      : debugdaemon_proxy_(NULL),
        weak_ptr_factory_(this),
        pipe_reader_(NULL) {
    debugdaemon_proxy_ = bus->GetObjectProxy(
        debugd::kDebugdServiceName,
        dbus::ObjectPath(debugd::kDebugdServicePath));
  }

  virtual ~DebugDaemonClientImpl() {}

  // DebugDaemonClient override.
  virtual void GetDebugLogs(base::PlatformFile file,
                            const GetDebugLogsCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kGetDebugLogs);
    dbus::MessageWriter writer(&method_call);
    dbus::FileDescriptor fd(file);  // explicit temp for C++ 98
    writer.AppendFileDescriptor(fd);

    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnGetDebugLogs,
                   weak_ptr_factory_.GetWeakPtr(),
                   callback));
  }

  virtual void SetDebugMode(const std::string& subsystem,
                            const SetDebugModeCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(debugd::kDebugdInterface,
                                 debugd::kSetDebugMode);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString(subsystem);
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnSetDebugMode,
                   weak_ptr_factory_.GetWeakPtr(),
                   callback));
  }

  virtual void StartSystemTracing() OVERRIDE {
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kSystraceStart);
    dbus::MessageWriter writer(&method_call);
    writer.AppendString("all"); // TODO(sleffler) parameterize category list

    DVLOG(1) << "Requesting a systrace start";
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnStartSystemTracing,
                   weak_ptr_factory_.GetWeakPtr()));
  }

  virtual bool RequestStopSystemTracing(const StopSystemTracingCallback&
      callback) OVERRIDE {
    if (pipe_reader_ != NULL) {
      LOG(ERROR) << "Busy doing StopSystemTracing";
      return false;
    }

    pipe_reader_.reset(new PipeReader(
        base::Bind(&DebugDaemonClientImpl::OnIOComplete,
                   weak_ptr_factory_.GetWeakPtr())));
    int write_fd = -1;
    if (!pipe_reader_->StartIO()) {
      LOG(ERROR) << "Cannot create pipe reader";
      // NB: continue anyway to shutdown tracing; toss trace data
      write_fd = HANDLE_EINTR(open("/dev/null", O_WRONLY));
      // TODO(sleffler) if this fails AppendFileDescriptor will abort
    } else {
      write_fd = pipe_reader_->GetWriteFD();
    }

    callback_ = callback;

    // Issue the dbus request to stop system tracing
    dbus::MethodCall method_call(
        debugd::kDebugdInterface,
        debugd::kSystraceStop);
    dbus::MessageWriter writer(&method_call);
    dbus::FileDescriptor temp(write_fd);  // NB: explicit temp for C++98
    writer.AppendFileDescriptor(temp);

    DVLOG(1) << "Requesting a systrace stop";
    debugdaemon_proxy_->CallMethod(
        &method_call,
        dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::Bind(&DebugDaemonClientImpl::OnRequestStopSystemTracing,
                   weak_ptr_factory_.GetWeakPtr()));

    pipe_reader_->CloseWriteFD();  // close our copy of fd after send

    return true;
  }

 private:
  // Called when a response for GetDebugLogs() is received.
  void OnGetDebugLogs(const GetDebugLogsCallback& callback,
                      dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to get debug logs";
      callback.Run(false);
      return;
    }
    callback.Run(true);
  }

  // Called when a response for SetDebugMode() is received.
  void OnSetDebugMode(const SetDebugModeCallback& callback,
                      dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to change debug mode";
      callback.Run(false);
    } else {
      callback.Run(true);
    }
  }

  // Called when a response for StartSystemTracing() is received.
  void OnStartSystemTracing(dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to request systrace start";
      return;
    }
  }

  // Called when a response for RequestStopSystemTracing() is received.
  void OnRequestStopSystemTracing(dbus::Response* response) {
    if (!response) {
      LOG(ERROR) << "Failed to request systrace stop";
      pipe_reader_->OnDataReady(-1); // terminate data stream
    }
    // NB: requester is signaled when i/o completes
  }

  // Called when pipe i/o completes; pass data on and delete the instance.
  void OnIOComplete() {
    callback_.Run(base::RefCountedString::TakeString(pipe_reader_->data()));
    pipe_reader_.reset();
  }

  dbus::ObjectProxy* debugdaemon_proxy_;
  base::WeakPtrFactory<DebugDaemonClientImpl> weak_ptr_factory_;
  scoped_ptr<PipeReader> pipe_reader_;
  StopSystemTracingCallback callback_;

  DISALLOW_COPY_AND_ASSIGN(DebugDaemonClientImpl);
};

// The DebugDaemonClient implementation used on Linux desktop,
// which does nothing.
class DebugDaemonClientStubImpl : public DebugDaemonClient {
  // DebugDaemonClient overrides.
  virtual void GetDebugLogs(base::PlatformFile file,
                            const GetDebugLogsCallback& callback) OVERRIDE {
    callback.Run(false);
  }
  virtual void SetDebugMode(const std::string& subsystem,
                            const SetDebugModeCallback& callback) OVERRIDE {
    callback.Run(false);
  }
  virtual void StartSystemTracing() OVERRIDE {}
  virtual bool RequestStopSystemTracing(const StopSystemTracingCallback&
      callback) OVERRIDE {
    std::string no_data;
    callback.Run(base::RefCountedString::TakeString(&no_data));
    return true;
  }
};

DebugDaemonClient::DebugDaemonClient() {
}

DebugDaemonClient::~DebugDaemonClient() {
}

// static
DebugDaemonClient::StopSystemTracingCallback
DebugDaemonClient::EmptyStopSystemTracingCallback() {
  return base::Bind(&EmptyStopSystemTracingCallbackBody);
}

// static
DebugDaemonClient* DebugDaemonClient::Create(DBusClientImplementationType type,
                                   dbus::Bus* bus) {
  if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
    return new DebugDaemonClientImpl(bus);
  DCHECK_EQ(STUB_DBUS_CLIENT_IMPLEMENTATION, type);
  return new DebugDaemonClientStubImpl();
}

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1461455 by johtaylo@johtaylo-jtincrementor-increment on 2017/09/21 03:00:48<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1170263 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/07/14 03:01:04<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1618388 by chui@ocl-promo-incrementor on 2018/10/13 03:01:02<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1092917 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/11/03 03:00:12<commit_after><|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  d3d11MeshFactory.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "d3d11MeshFactory.h"
#include "d3d11_impl.h"
#include "Gfx/Core/renderer.h"
#include "Gfx/Resource/resourcePools.h"
#include "Gfx/d3d11/d3d11Types.h"

namespace Oryol {
namespace _priv {

//------------------------------------------------------------------------------
d3d11MeshFactory::d3d11MeshFactory() :
renderer(nullptr),
meshPool(nullptr),
d3d11Device(nullptr),
isValid(false) {
    // empty
}

//------------------------------------------------------------------------------
d3d11MeshFactory::~d3d11MeshFactory() {
    o_assert_dbg(!this->isValid);
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::Setup(class renderer* rendr, class meshPool* mshPool) {
    o_assert_dbg(!this->isValid);
    o_assert_dbg(rendr);
    o_assert_dbg(mshPool);
    o_assert_dbg(rendr->d3d11Device);

    this->isValid = true;
    this->renderer = rendr;
    this->meshPool = mshPool;
    this->d3d11Device = renderer->d3d11Device;
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::Discard() {
    o_assert_dbg(this->isValid);
    this->isValid = false;
    this->renderer = nullptr;
    this->meshPool = nullptr;
    this->d3d11Device = nullptr;
}

//------------------------------------------------------------------------------
bool
d3d11MeshFactory::IsValid() const {
    return this->isValid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::SetupResource(mesh& msh) {
    o_assert_dbg(this->isValid);
    if (msh.Setup.ShouldSetupEmpty()) {
        return this->createEmptyMesh(msh);
    }
    else if (msh.Setup.ShouldSetupFullScreenQuad()) {
        return this->createFullscreenQuad(msh);
    }
    else {
        o_error("d3d11MeshFactory::SetupResource(): don't know how to create mesh!");
        return ResourceState::InvalidState;
    }
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::SetupResource(mesh& msh, const void* data, int32 size) {
    o_assert_dbg(msh.Setup.ShouldSetupFromData());
    return this->createFromData(msh, data, size);
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::DestroyResource(mesh& mesh) {
    o_assert_dbg(nullptr != this->renderer);

    this->renderer->invalidateMeshState();

    if (mesh.d3d11VertexBuffer) {
        mesh.d3d11VertexBuffer->Release();
    }
    if (mesh.d3d11IndexBuffer) {
        mesh.d3d11IndexBuffer->Release();
    }
    mesh.Clear();
}

//------------------------------------------------------------------------------
ID3D11Buffer*
d3d11MeshFactory::createBuffer(const void* data, uint32 dataSize, uint32 d3d11BindFlags, Usage::Code usage) {
    o_assert_dbg(this->d3d11Device);
    o_assert_dbg((D3D11_BIND_VERTEX_BUFFER == d3d11BindFlags) || (D3D11_BIND_INDEX_BUFFER == d3d11BindFlags));

    D3D11_BUFFER_DESC desc;
    Memory::Clear(&desc, sizeof(desc));
    desc.ByteWidth = dataSize;
    desc.Usage = d3d11Types::asBufferUsage(usage);
    desc.BindFlags = d3d11BindFlags;
    desc.CPUAccessFlags = d3d11Types::asBufferCPUAccessFlag(usage);

    D3D11_SUBRESOURCE_DATA* initDataPtr = nullptr;
    D3D11_SUBRESOURCE_DATA initData;
    Memory::Clear(&initData, sizeof(initData));
    if (data) {
        initData.pSysMem = data;
        initDataPtr = &initData;
    }
    ID3D11Buffer* buf = nullptr;
    HRESULT hr = this->d3d11Device->CreateBuffer(&desc, initDataPtr, &buf);
    o_assert(SUCCEEDED(hr));
    o_assert_dbg(buf);

    return buf;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createFullscreenQuad(mesh& mesh) {
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);

    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = 4;
    vbAttrs.BufferUsage = Usage::Immutable;
    vbAttrs.Layout.Add(VertexAttr::Position, VertexFormat::Float3);
    vbAttrs.Layout.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
    vbAttrs.StepFunction = VertexStepFunction::PerVertex;
    vbAttrs.StepRate = 1;
    mesh.vertexBufferAttrs = vbAttrs;

    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = 6;
    ibAttrs.Type = IndexType::Index16;
    ibAttrs.BufferUsage = Usage::Immutable;
    mesh.indexBufferAttrs = ibAttrs;

    mesh.numPrimGroups = 1;
    mesh.primGroups[0] = PrimitiveGroup(PrimitiveType::Triangles, 0, 6);

    // vertices
    const float32 topV = mesh.Setup.FullScreenQuadFlipV ? 0.0f : 1.0f;
    const float32 botV = mesh.Setup.FullScreenQuadFlipV ? 1.0f : 0.0f;
    float32 vertices[] = {
        -1.0f, +1.0f, 0.0f, 0.0f, topV,     // top-left corner
        +1.0f, +1.0f, 0.0f, 1.0f, topV,     // top-right corner
        +1.0f, -1.0f, 0.0f, 1.0f, botV,     // bottom-right corner
        -1.0f, -1.0f, 0.0f, 0.0f, botV      // bottom-left corner
    };

    // indices
    uint16 indices[] = {
        0, 2, 1,            // topleft -> bottomright -> topright
        0, 3, 2,            // topleft -> bottomleft -> bottomright
    };

    // create vertex and index buffer
    mesh.d3d11VertexBuffer = this->createBuffer(vertices, sizeof(vertices), D3D11_BIND_VERTEX_BUFFER, mesh.vertexBufferAttrs.BufferUsage);
    mesh.d3d11IndexBuffer = this->createBuffer(indices, sizeof(indices), D3D11_BIND_INDEX_BUFFER, mesh.indexBufferAttrs.BufferUsage);

    return ResourceState::Valid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createEmptyMesh(mesh& mesh) {
    o_assert_dbg(0 < mesh.Setup.NumVertices);
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);

    const MeshSetup& setup = mesh.Setup;

    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = setup.NumVertices;
    vbAttrs.Layout = setup.Layout;
    vbAttrs.BufferUsage = setup.VertexUsage;
    vbAttrs.StepFunction = setup.StepFunction;
    vbAttrs.StepRate = setup.StepRate;
    mesh.vertexBufferAttrs = vbAttrs;
    const int32 vbSize = vbAttrs.NumVertices * vbAttrs.Layout.ByteSize();

    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = setup.NumIndices;
    ibAttrs.Type = setup.IndicesType;
    ibAttrs.BufferUsage = setup.IndexUsage;
    mesh.indexBufferAttrs = ibAttrs;
    const int32 ibSize = ibAttrs.NumIndices * IndexType::ByteSize(ibAttrs.Type);

    mesh.numPrimGroups = setup.NumPrimitiveGroups();
    o_assert_dbg(mesh.numPrimGroups < GfxConfig::MaxNumPrimGroups);
    for (int32 i = 0; i < mesh.numPrimGroups; i++) {
        mesh.primGroups[i] = setup.PrimitiveGroup(i);
    }

    mesh.d3d11VertexBuffer = this->createBuffer(nullptr, vbSize, D3D11_BIND_VERTEX_BUFFER, vbAttrs.BufferUsage);
    if (IndexType::None != ibAttrs.Type) {
        mesh.d3d11IndexBuffer  = this->createBuffer(nullptr, ibSize, D3D11_BIND_INDEX_BUFFER, ibAttrs.BufferUsage);
    }

    return ResourceState::Valid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createFromData(mesh& mesh, const void* data, int32 size) {
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);
    o_assert_dbg(nullptr != data);
    o_assert_dbg(size > 0);

    const MeshSetup& setup = mesh.Setup;

    // setup vertex buffer attrs
    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = setup.NumVertices;
    vbAttrs.BufferUsage = setup.VertexUsage;
    vbAttrs.Layout = setup.Layout;
    vbAttrs.StepFunction = setup.StepFunction;
    vbAttrs.StepRate = setup.StepRate;
    mesh.vertexBufferAttrs = vbAttrs;

    // setup index buffer attrs
    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = setup.NumIndices;
    ibAttrs.Type = setup.IndicesType;
    ibAttrs.BufferUsage = setup.IndexUsage;
    mesh.indexBufferAttrs = ibAttrs;

    // setup primitive groups
    mesh.numPrimGroups = setup.NumPrimitiveGroups();
    o_assert_dbg(mesh.numPrimGroups < GfxConfig::MaxNumPrimGroups);
    for (int32 i = 0; i < mesh.numPrimGroups; i++) {
        mesh.primGroups[i] = setup.PrimitiveGroup(i);
    }

    // setup the mesh object
    const uint8* ptr = (const uint8*)data;
    const uint8* vertices = ptr + setup.DataVertexOffset;
    const int32 verticesByteSize = setup.NumVertices * setup.Layout.ByteSize();
    o_assert_dbg((ptr + size) >= (vertices + verticesByteSize));
    mesh.d3d11VertexBuffer = this->createBuffer(vertices, verticesByteSize, D3D11_BIND_VERTEX_BUFFER, setup.VertexUsage);
    if (setup.IndicesType != IndexType::None) {
        o_assert_dbg(setup.DataIndexOffset != InvalidIndex);
        o_assert_dbg(setup.DataIndexOffset >= verticesByteSize);
        const uint8* indices = ((const uint8*)ptr) + setup.DataIndexOffset;
        const int32 indicesByteSize = setup.NumIndices * IndexType::ByteSize(setup.IndicesType);
        o_assert_dbg((ptr + size) >= (indices + indicesByteSize));
        mesh.d3d11IndexBuffer = this->createBuffer(indices, indicesByteSize, D3D11_BIND_INDEX_BUFFER, setup.IndexUsage);
    }
    return ResourceState::Valid;
}

} // namespace _priv
} // namespace Oryol<commit_msg>Small fix in d3d11MeshFactory<commit_after>//------------------------------------------------------------------------------
//  d3d11MeshFactory.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "d3d11MeshFactory.h"
#include "d3d11_impl.h"
#include "Gfx/Core/renderer.h"
#include "Gfx/Resource/resourcePools.h"
#include "Gfx/d3d11/d3d11Types.h"

namespace Oryol {
namespace _priv {

//------------------------------------------------------------------------------
d3d11MeshFactory::d3d11MeshFactory() :
renderer(nullptr),
meshPool(nullptr),
d3d11Device(nullptr),
isValid(false) {
    // empty
}

//------------------------------------------------------------------------------
d3d11MeshFactory::~d3d11MeshFactory() {
    o_assert_dbg(!this->isValid);
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::Setup(class renderer* rendr, class meshPool* mshPool) {
    o_assert_dbg(!this->isValid);
    o_assert_dbg(rendr);
    o_assert_dbg(mshPool);
    o_assert_dbg(rendr->d3d11Device);

    this->isValid = true;
    this->renderer = rendr;
    this->meshPool = mshPool;
    this->d3d11Device = renderer->d3d11Device;
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::Discard() {
    o_assert_dbg(this->isValid);
    this->isValid = false;
    this->renderer = nullptr;
    this->meshPool = nullptr;
    this->d3d11Device = nullptr;
}

//------------------------------------------------------------------------------
bool
d3d11MeshFactory::IsValid() const {
    return this->isValid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::SetupResource(mesh& msh) {
    o_assert_dbg(this->isValid);
    if (msh.Setup.ShouldSetupEmpty()) {
        return this->createEmptyMesh(msh);
    }
    else if (msh.Setup.ShouldSetupFullScreenQuad()) {
        return this->createFullscreenQuad(msh);
    }
    else {
        o_error("d3d11MeshFactory::SetupResource(): don't know how to create mesh!");
        return ResourceState::InvalidState;
    }
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::SetupResource(mesh& msh, const void* data, int32 size) {
    o_assert_dbg(msh.Setup.ShouldSetupFromData());
    return this->createFromData(msh, data, size);
}

//------------------------------------------------------------------------------
void
d3d11MeshFactory::DestroyResource(mesh& mesh) {
    o_assert_dbg(nullptr != this->renderer);

    this->renderer->invalidateMeshState();

    if (mesh.d3d11VertexBuffer) {
        mesh.d3d11VertexBuffer->Release();
    }
    if (mesh.d3d11IndexBuffer) {
        mesh.d3d11IndexBuffer->Release();
    }
    mesh.Clear();
}

//------------------------------------------------------------------------------
ID3D11Buffer*
d3d11MeshFactory::createBuffer(const void* data, uint32 dataSize, uint32 d3d11BindFlags, Usage::Code usage) {
    o_assert_dbg(this->d3d11Device);
    o_assert_dbg((D3D11_BIND_VERTEX_BUFFER == d3d11BindFlags) || (D3D11_BIND_INDEX_BUFFER == d3d11BindFlags));

    D3D11_BUFFER_DESC desc;
    Memory::Clear(&desc, sizeof(desc));
    desc.ByteWidth = dataSize;
    desc.Usage = d3d11Types::asBufferUsage(usage);
    desc.BindFlags = d3d11BindFlags;
    desc.CPUAccessFlags = d3d11Types::asBufferCPUAccessFlag(usage);

    D3D11_SUBRESOURCE_DATA* initDataPtr = nullptr;
    D3D11_SUBRESOURCE_DATA initData;
    Memory::Clear(&initData, sizeof(initData));
    if (data) {
        initData.pSysMem = data;
        initDataPtr = &initData;
    }
    ID3D11Buffer* buf = nullptr;
    HRESULT hr = this->d3d11Device->CreateBuffer(&desc, initDataPtr, &buf);
    o_assert(SUCCEEDED(hr));
    o_assert_dbg(buf);

    return buf;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createFullscreenQuad(mesh& mesh) {
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);

    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = 4;
    vbAttrs.BufferUsage = Usage::Immutable;
    vbAttrs.Layout.Add(VertexAttr::Position, VertexFormat::Float3);
    vbAttrs.Layout.Add(VertexAttr::TexCoord0, VertexFormat::Float2);
    vbAttrs.StepFunction = VertexStepFunction::PerVertex;
    vbAttrs.StepRate = 1;
    mesh.vertexBufferAttrs = vbAttrs;

    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = 6;
    ibAttrs.Type = IndexType::Index16;
    ibAttrs.BufferUsage = Usage::Immutable;
    mesh.indexBufferAttrs = ibAttrs;

    mesh.numPrimGroups = 1;
    mesh.primGroups[0] = PrimitiveGroup(PrimitiveType::Triangles, 0, 6);

    // vertices
    const float32 topV = mesh.Setup.FullScreenQuadFlipV ? 0.0f : 1.0f;
    const float32 botV = mesh.Setup.FullScreenQuadFlipV ? 1.0f : 0.0f;
    float32 vertices[] = {
        -1.0f, +1.0f, 0.0f, 0.0f, topV,     // top-left corner
        +1.0f, +1.0f, 0.0f, 1.0f, topV,     // top-right corner
        +1.0f, -1.0f, 0.0f, 1.0f, botV,     // bottom-right corner
        -1.0f, -1.0f, 0.0f, 0.0f, botV      // bottom-left corner
    };

    // indices
    uint16 indices[] = {
        0, 2, 1,            // topleft -> bottomright -> topright
        0, 3, 2,            // topleft -> bottomleft -> bottomright
    };

    // create vertex and index buffer
    mesh.d3d11VertexBuffer = this->createBuffer(vertices, sizeof(vertices), D3D11_BIND_VERTEX_BUFFER, mesh.vertexBufferAttrs.BufferUsage);
    mesh.d3d11IndexBuffer = this->createBuffer(indices, sizeof(indices), D3D11_BIND_INDEX_BUFFER, mesh.indexBufferAttrs.BufferUsage);

    return ResourceState::Valid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createEmptyMesh(mesh& mesh) {
    o_assert_dbg(0 < mesh.Setup.NumVertices);
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);

    const MeshSetup& setup = mesh.Setup;

    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = setup.NumVertices;
    vbAttrs.Layout = setup.Layout;
    vbAttrs.BufferUsage = setup.VertexUsage;
    vbAttrs.StepFunction = setup.StepFunction;
    vbAttrs.StepRate = setup.StepRate;
    mesh.vertexBufferAttrs = vbAttrs;
    const int32 vbSize = vbAttrs.NumVertices * vbAttrs.Layout.ByteSize();

    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = setup.NumIndices;
    ibAttrs.Type = setup.IndicesType;
    ibAttrs.BufferUsage = setup.IndexUsage;
    mesh.indexBufferAttrs = ibAttrs;

    mesh.numPrimGroups = setup.NumPrimitiveGroups();
    o_assert_dbg(mesh.numPrimGroups < GfxConfig::MaxNumPrimGroups);
    for (int32 i = 0; i < mesh.numPrimGroups; i++) {
        mesh.primGroups[i] = setup.PrimitiveGroup(i);
    }

    mesh.d3d11VertexBuffer = this->createBuffer(nullptr, vbSize, D3D11_BIND_VERTEX_BUFFER, vbAttrs.BufferUsage);
    if (IndexType::None != ibAttrs.Type) {
        const int32 ibSize = ibAttrs.NumIndices * IndexType::ByteSize(ibAttrs.Type);
        mesh.d3d11IndexBuffer  = this->createBuffer(nullptr, ibSize, D3D11_BIND_INDEX_BUFFER, ibAttrs.BufferUsage);
    }

    return ResourceState::Valid;
}

//------------------------------------------------------------------------------
ResourceState::Code
d3d11MeshFactory::createFromData(mesh& mesh, const void* data, int32 size) {
    o_assert_dbg(nullptr == mesh.d3d11VertexBuffer);
    o_assert_dbg(nullptr == mesh.d3d11IndexBuffer);
    o_assert_dbg(nullptr != data);
    o_assert_dbg(size > 0);

    const MeshSetup& setup = mesh.Setup;

    // setup vertex buffer attrs
    VertexBufferAttrs vbAttrs;
    vbAttrs.NumVertices = setup.NumVertices;
    vbAttrs.BufferUsage = setup.VertexUsage;
    vbAttrs.Layout = setup.Layout;
    vbAttrs.StepFunction = setup.StepFunction;
    vbAttrs.StepRate = setup.StepRate;
    mesh.vertexBufferAttrs = vbAttrs;

    // setup index buffer attrs
    IndexBufferAttrs ibAttrs;
    ibAttrs.NumIndices = setup.NumIndices;
    ibAttrs.Type = setup.IndicesType;
    ibAttrs.BufferUsage = setup.IndexUsage;
    mesh.indexBufferAttrs = ibAttrs;

    // setup primitive groups
    mesh.numPrimGroups = setup.NumPrimitiveGroups();
    o_assert_dbg(mesh.numPrimGroups < GfxConfig::MaxNumPrimGroups);
    for (int32 i = 0; i < mesh.numPrimGroups; i++) {
        mesh.primGroups[i] = setup.PrimitiveGroup(i);
    }

    // setup the mesh object
    const uint8* ptr = (const uint8*)data;
    const uint8* vertices = ptr + setup.DataVertexOffset;
    const int32 verticesByteSize = setup.NumVertices * setup.Layout.ByteSize();
    o_assert_dbg((ptr + size) >= (vertices + verticesByteSize));
    mesh.d3d11VertexBuffer = this->createBuffer(vertices, verticesByteSize, D3D11_BIND_VERTEX_BUFFER, setup.VertexUsage);
    if (setup.IndicesType != IndexType::None) {
        o_assert_dbg(setup.DataIndexOffset != InvalidIndex);
        o_assert_dbg(setup.DataIndexOffset >= verticesByteSize);
        const uint8* indices = ((const uint8*)ptr) + setup.DataIndexOffset;
        const int32 indicesByteSize = setup.NumIndices * IndexType::ByteSize(setup.IndicesType);
        o_assert_dbg((ptr + size) >= (indices + indicesByteSize));
        mesh.d3d11IndexBuffer = this->createBuffer(indices, indicesByteSize, D3D11_BIND_INDEX_BUFFER, setup.IndexUsage);
    }
    return ResourceState::Valid;
}

} // namespace _priv
} // namespace Oryol
<|endoftext|>


<commit_before><commit_msg>#i10000# include algorithm<commit_after><|endoftext|>


<commit_before>/**
 * This file is part of the "libstx" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * libstx is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <string>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stx/buffer.h>
#include <stx/exception.h>
#include <stx/io/inputstream.h>
#include <stx/ieee754.h>

namespace stx {

std::unique_ptr<InputStream> InputStream::getStdin() {
  auto stdin_stream = new FileInputStream(0, false);
  return std::unique_ptr<InputStream>(stdin_stream);
}

InputStream::InputStream(
    const std::string& filename /* = "<anonymous input stream>" */) :
    filename_(filename) {}

const std::string& InputStream::getFileName() const {
  return filename_;
}

void InputStream::setFileName(const std::string& filename) {
  filename_ = filename;
}

// FIXPAUL: optimize?
size_t InputStream::readNextBytes(std::string* target, size_t n_bytes) {
  char byte;
  size_t length;

  for (length = 0; length < n_bytes && readNextByte(&byte); ++length) {
    *target += byte;
  }

  return length;
}

// FIXPAUL: optimize?
size_t InputStream::readNextBytes(Buffer* target, size_t n_bytes) {
  char byte;
  size_t length;

  target->reserve(n_bytes);

  for (length = 0; length < n_bytes && readNextByte(&byte); ++length) {
    target->append(&byte, sizeof(byte));
  }

  return length;
}

size_t InputStream::readNextBytes(void* target, size_t n_bytes) {
  size_t length = 0;

  while (length < n_bytes && readNextByte(((char*) target) + length)) {
    ++length;
  }

  return length;
}

// FIXPAUL: optimize?
size_t InputStream::readUntilEOF(std::string* target) {
  char byte;
  size_t length;

  for (length = 0; readNextByte(&byte); ++length) {
    *target += byte;
  }

  return length;
}

bool InputStream::readLine(std::string* target) {
  char byte;
  size_t length;

  for (length = 0; readNextByte(&byte); ++length) {
    *target += byte;

    if (byte == '\n') {
      return true;
    }
  }

  return false;
}

uint8_t InputStream::readUInt8() {
  uint8_t val;
  if (readNextBytes(&val, sizeof(uint8_t)) != sizeof(uint8_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint16_t InputStream::readUInt16() {
  uint16_t val;
  if (readNextBytes(&val, sizeof(uint16_t)) != sizeof(uint16_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint32_t InputStream::readUInt32() {
  uint32_t val;
  if (readNextBytes(&val, sizeof(uint32_t)) != sizeof(uint32_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint64_t InputStream::readUInt64() {
  uint64_t val;
  if (readNextBytes(&val, sizeof(uint64_t)) != sizeof(uint64_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint64_t InputStream::readVarUInt() {
  uint64_t val = 0;

  for (int i = 0; ; ++i) {
    unsigned char b;
    readNextByte((char*) &b);

    val |= (b & 0x7fULL) << (7 * i);

    if (!(b & 0x80U)) {
      break;
    }
  }

  return val;
}

String InputStream::readString(size_t size) {
  String val;
  if (readNextBytes(&val, size) != size) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

String InputStream::readLenencString() {
  auto size = readVarUInt();

  String val;
  if (readNextBytes(&val, size) != size) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

double InputStream::readDouble() {
  uint64_t val;
  if (readNextBytes(&val, sizeof(uint64_t)) != sizeof(uint64_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return IEEE754::fromBytes(val);
}

std::unique_ptr<FileInputStream> FileInputStream::openFile(
    const std::string& file_path) {
  auto fp = file_path.c_str();
  int fd = open(fp, O_RDONLY);

  if (fd < 1) {
    RAISE_ERRNO(kIOError, "error opening file '%s'", fp);
  }

  std::unique_ptr<FileInputStream> stream(new FileInputStream(fd, true));
  stream->readNextChunk();
  stream->setFileName(file_path);
  return stream;
}

std::unique_ptr<FileInputStream> FileInputStream::fromFileDescriptor(
    int fd,
    bool close_on_destroy /* = false */) {
  std::unique_ptr<FileInputStream> stream(
      new FileInputStream(fd, close_on_destroy));

  stream->setFileName(StringUtil::format("<fd:$0>", fd));
  return stream;
}

std::unique_ptr<FileInputStream> FileInputStream::fromFile(File&& file) {
  auto fd = file.fd();

  std::unique_ptr<FileInputStream> stream(new FileInputStream(std::move(file)));
  stream->setFileName(StringUtil::format("<fd:$0>", fd));
  return stream;
}

FileInputStream::FileInputStream(
    int fd,
    bool close_on_destroy /* = false */) :
    fd_(fd),
    close_on_destroy_(close_on_destroy),
    buf_len_(0),
    buf_pos_(0) {}

FileInputStream::FileInputStream(
    File&& file) :
    FileInputStream(file.releaseFD(), true) {}

FileInputStream::~FileInputStream() {
  if (fd_ >= 0 && close_on_destroy_) {
    close(fd_);
  }
}

bool FileInputStream::readNextByte(char* target) {
  if (buf_pos_ >= buf_len_) {
    readNextChunk();
  }

  if (buf_pos_ < buf_len_) {
    *target = buf_[buf_pos_++];
    return true;
  } else {
    return false;
  }
}

bool FileInputStream::eof() {
  if (buf_pos_ >= buf_len_) {
    readNextChunk();
  }

  return buf_pos_ >= buf_len_;
}

// FIXPAUL move somwhere else...
FileInputStream::kByteOrderMark FileInputStream::readByteOrderMark() {
  static char kByteOrderMarkUTF8[] = "\xEF\xBB\xBF";
  if (buf_pos_ + 2 < buf_len_ &&
      strncmp(buf_ + buf_pos_, kByteOrderMarkUTF8, 3) == 0) {
    buf_pos_ += 3;
    return BOM_UTF8;
  }

  return BOM_UNKNOWN;
}

void FileInputStream::readNextChunk() {
  int bytes_read = read(fd_, buf_, sizeof(buf_));

  if (bytes_read < 0) {
    RAISE_ERRNO(kIOError, "read(%s) failed", getFileName().c_str());
  }

  buf_pos_ = 0;
  buf_len_ = bytes_read;
}

void FileInputStream::rewind() {
  buf_pos_ = 0;
  buf_len_ = 0;

  if (lseek(fd_, 0, SEEK_SET) < 0) {
    RAISE_ERRNO(kIOError, "lseek(%s) failed", getFileName().c_str());
  }
}

std::unique_ptr<StringInputStream> StringInputStream::fromString(
    const std::string& string) {
  return std::unique_ptr<StringInputStream>(new StringInputStream(string));
}

StringInputStream::StringInputStream(
    const std::string& string) :
    str_(string),
    cur_(0) {
}

bool StringInputStream::readNextByte(char* target) {
  if (cur_ < str_.size()) {
    *target = str_[cur_++];
    return true;
  } else {
    return false;
  }
}

bool StringInputStream::eof() {
  return cur_ >= str_.size();
}

void StringInputStream::rewind() {
  cur_ = 0;
}

std::unique_ptr<BufferInputStream> BufferInputStream::fromBuffer(
    const Buffer* buf) {
  return std::unique_ptr<BufferInputStream>(new BufferInputStream(buf));
}

BufferInputStream::BufferInputStream(
    const Buffer* buf) :
    buf_(buf),
    cur_(0) {
}

bool BufferInputStream::readNextByte(char* target) {
  if (cur_ < buf_->size()) {
    *target = buf_->charAt(cur_++);
    return true;
  } else {
    return false;
  }
}

bool BufferInputStream::eof() {
  return cur_ >= buf_->size();
}

void BufferInputStream::rewind() {
  cur_ = 0;
}

MemoryInputStream::MemoryInputStream(
    const void* data,
    size_t size) :
    data_(data),
    size_(size),
    cur_(0) {}

bool MemoryInputStream::readNextByte(char* target) {
  if (cur_ < size_) {
    *target = *(((char*) data_) + cur_++);
    return true;
  } else {
    return false;
  }
}

bool MemoryInputStream::eof() {
  return cur_ >= size_;
}

void MemoryInputStream::rewind() {
  cur_ = 0;
}

} // namespace stx

<commit_msg>don't return EOF yet if we read some bytes before it happened in InputStream::readLine<commit_after>/**
 * This file is part of the "libstx" project
 *   Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
 *
 * libstx is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <string>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stx/buffer.h>
#include <stx/exception.h>
#include <stx/io/inputstream.h>
#include <stx/ieee754.h>

namespace stx {

std::unique_ptr<InputStream> InputStream::getStdin() {
  auto stdin_stream = new FileInputStream(0, false);
  return std::unique_ptr<InputStream>(stdin_stream);
}

InputStream::InputStream(
    const std::string& filename /* = "<anonymous input stream>" */) :
    filename_(filename) {}

const std::string& InputStream::getFileName() const {
  return filename_;
}

void InputStream::setFileName(const std::string& filename) {
  filename_ = filename;
}

// FIXPAUL: optimize?
size_t InputStream::readNextBytes(std::string* target, size_t n_bytes) {
  char byte;
  size_t length;

  for (length = 0; length < n_bytes && readNextByte(&byte); ++length) {
    *target += byte;
  }

  return length;
}

// FIXPAUL: optimize?
size_t InputStream::readNextBytes(Buffer* target, size_t n_bytes) {
  char byte;
  size_t length;

  target->reserve(n_bytes);

  for (length = 0; length < n_bytes && readNextByte(&byte); ++length) {
    target->append(&byte, sizeof(byte));
  }

  return length;
}

size_t InputStream::readNextBytes(void* target, size_t n_bytes) {
  size_t length = 0;

  while (length < n_bytes && readNextByte(((char*) target) + length)) {
    ++length;
  }

  return length;
}

// FIXPAUL: optimize?
size_t InputStream::readUntilEOF(std::string* target) {
  char byte;
  size_t length;

  for (length = 0; readNextByte(&byte); ++length) {
    *target += byte;
  }

  return length;
}

bool InputStream::readLine(std::string* target) {
  char byte;
  size_t length;

  for (length = 0; readNextByte(&byte); ++length) {
    *target += byte;

    if (byte == '\n') {
      return true;
    }
  }

  return length > 0;
}

uint8_t InputStream::readUInt8() {
  uint8_t val;
  if (readNextBytes(&val, sizeof(uint8_t)) != sizeof(uint8_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint16_t InputStream::readUInt16() {
  uint16_t val;
  if (readNextBytes(&val, sizeof(uint16_t)) != sizeof(uint16_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint32_t InputStream::readUInt32() {
  uint32_t val;
  if (readNextBytes(&val, sizeof(uint32_t)) != sizeof(uint32_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint64_t InputStream::readUInt64() {
  uint64_t val;
  if (readNextBytes(&val, sizeof(uint64_t)) != sizeof(uint64_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

uint64_t InputStream::readVarUInt() {
  uint64_t val = 0;

  for (int i = 0; ; ++i) {
    unsigned char b;
    readNextByte((char*) &b);

    val |= (b & 0x7fULL) << (7 * i);

    if (!(b & 0x80U)) {
      break;
    }
  }

  return val;
}

String InputStream::readString(size_t size) {
  String val;
  if (readNextBytes(&val, size) != size) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

String InputStream::readLenencString() {
  auto size = readVarUInt();

  String val;
  if (readNextBytes(&val, size) != size) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return val;
}

double InputStream::readDouble() {
  uint64_t val;
  if (readNextBytes(&val, sizeof(uint64_t)) != sizeof(uint64_t)) {
    RAISE(kEOFError, "unexpected end of stream");
  }

  return IEEE754::fromBytes(val);
}

std::unique_ptr<FileInputStream> FileInputStream::openFile(
    const std::string& file_path) {
  auto fp = file_path.c_str();
  int fd = open(fp, O_RDONLY);

  if (fd < 1) {
    RAISE_ERRNO(kIOError, "error opening file '%s'", fp);
  }

  std::unique_ptr<FileInputStream> stream(new FileInputStream(fd, true));
  stream->readNextChunk();
  stream->setFileName(file_path);
  return stream;
}

std::unique_ptr<FileInputStream> FileInputStream::fromFileDescriptor(
    int fd,
    bool close_on_destroy /* = false */) {
  std::unique_ptr<FileInputStream> stream(
      new FileInputStream(fd, close_on_destroy));

  stream->setFileName(StringUtil::format("<fd:$0>", fd));
  return stream;
}

std::unique_ptr<FileInputStream> FileInputStream::fromFile(File&& file) {
  auto fd = file.fd();

  std::unique_ptr<FileInputStream> stream(new FileInputStream(std::move(file)));
  stream->setFileName(StringUtil::format("<fd:$0>", fd));
  return stream;
}

FileInputStream::FileInputStream(
    int fd,
    bool close_on_destroy /* = false */) :
    fd_(fd),
    close_on_destroy_(close_on_destroy),
    buf_len_(0),
    buf_pos_(0) {}

FileInputStream::FileInputStream(
    File&& file) :
    FileInputStream(file.releaseFD(), true) {}

FileInputStream::~FileInputStream() {
  if (fd_ >= 0 && close_on_destroy_) {
    close(fd_);
  }
}

bool FileInputStream::readNextByte(char* target) {
  if (buf_pos_ >= buf_len_) {
    readNextChunk();
  }

  if (buf_pos_ < buf_len_) {
    *target = buf_[buf_pos_++];
    return true;
  } else {
    return false;
  }
}

bool FileInputStream::eof() {
  if (buf_pos_ >= buf_len_) {
    readNextChunk();
  }

  return buf_pos_ >= buf_len_;
}

// FIXPAUL move somwhere else...
FileInputStream::kByteOrderMark FileInputStream::readByteOrderMark() {
  static char kByteOrderMarkUTF8[] = "\xEF\xBB\xBF";
  if (buf_pos_ + 2 < buf_len_ &&
      strncmp(buf_ + buf_pos_, kByteOrderMarkUTF8, 3) == 0) {
    buf_pos_ += 3;
    return BOM_UTF8;
  }

  return BOM_UNKNOWN;
}

void FileInputStream::readNextChunk() {
  int bytes_read = read(fd_, buf_, sizeof(buf_));

  if (bytes_read < 0) {
    RAISE_ERRNO(kIOError, "read(%s) failed", getFileName().c_str());
  }

  buf_pos_ = 0;
  buf_len_ = bytes_read;
}

void FileInputStream::rewind() {
  buf_pos_ = 0;
  buf_len_ = 0;

  if (lseek(fd_, 0, SEEK_SET) < 0) {
    RAISE_ERRNO(kIOError, "lseek(%s) failed", getFileName().c_str());
  }
}

std::unique_ptr<StringInputStream> StringInputStream::fromString(
    const std::string& string) {
  return std::unique_ptr<StringInputStream>(new StringInputStream(string));
}

StringInputStream::StringInputStream(
    const std::string& string) :
    str_(string),
    cur_(0) {
}

bool StringInputStream::readNextByte(char* target) {
  if (cur_ < str_.size()) {
    *target = str_[cur_++];
    return true;
  } else {
    return false;
  }
}

bool StringInputStream::eof() {
  return cur_ >= str_.size();
}

void StringInputStream::rewind() {
  cur_ = 0;
}

std::unique_ptr<BufferInputStream> BufferInputStream::fromBuffer(
    const Buffer* buf) {
  return std::unique_ptr<BufferInputStream>(new BufferInputStream(buf));
}

BufferInputStream::BufferInputStream(
    const Buffer* buf) :
    buf_(buf),
    cur_(0) {
}

bool BufferInputStream::readNextByte(char* target) {
  if (cur_ < buf_->size()) {
    *target = buf_->charAt(cur_++);
    return true;
  } else {
    return false;
  }
}

bool BufferInputStream::eof() {
  return cur_ >= buf_->size();
}

void BufferInputStream::rewind() {
  cur_ = 0;
}

MemoryInputStream::MemoryInputStream(
    const void* data,
    size_t size) :
    data_(data),
    size_(size),
    cur_(0) {}

bool MemoryInputStream::readNextByte(char* target) {
  if (cur_ < size_) {
    *target = *(((char*) data_) + cur_++);
    return true;
  } else {
    return false;
  }
}

bool MemoryInputStream::eof() {
  return cur_ >= size_;
}

void MemoryInputStream::rewind() {
  cur_ = 0;
}

} // namespace stx

<|endoftext|>


<commit_before><commit_msg>Reordered `#include` lines into alphabetical order.<commit_after><|endoftext|>


<commit_before><commit_msg>Use `const std::string&` instead of `const std::string` in `for` loop.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: commonjava.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 11:57:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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 library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "sal/config.h"

#include "codemaker/commonjava.hxx"

#include "codemaker/options.hxx"
#include "codemaker/typemanager.hxx"
#include "codemaker/unotype.hxx"

#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "registry/types.h"
#include "rtl/strbuf.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"

#include <vector>

namespace codemaker { namespace java {

rtl::OString translateUnoToJavaType(
    codemaker::UnoType::Sort sort, RTTypeClass typeClass,
    rtl::OString const & nucleus, bool referenceType)
{
    rtl::OStringBuffer buf;
    if (sort == codemaker::UnoType::SORT_COMPLEX) {
        if (typeClass == RT_TYPE_INTERFACE
            && nucleus == rtl::OString("com/sun/star/uno/XInterface"))
        {
            buf.append(RTL_CONSTASCII_STRINGPARAM("java/lang/Object"));
        } else {
            //TODO: check that nucleus is a valid (Java-modified UTF-8)
            // identifier
            buf.append(nucleus);
        }
    } else {
        rtl::OString const javaTypes[codemaker::UnoType::SORT_ANY + 1][2] = {
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("void")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Void")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("boolean")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Boolean")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("byte")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Byte")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("short")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Short")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("short")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Short")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("int")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Integer")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("int")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Integer")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("long")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Long")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("long")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Long")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("float")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Float")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("double")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Double")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("char")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Character")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/String")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/String")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("com/sun/star/uno/Type")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("com/sun/star/uno/Type"))
            },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Object")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Object")) } };
        buf.append(javaTypes[sort][referenceType]);
    }
    return buf.makeStringAndClear();
}

rtl::OString translateUnoToJavaIdentifier(
    rtl::OString const & identifier, rtl::OString const & prefix)
{
    if (identifier == "abstract"
        || identifier == "assert" // since Java 1.4
        || identifier == "boolean"
        || identifier == "break"
        || identifier == "byte"
        || identifier == "case"
        || identifier == "catch"
        || identifier == "char"
        || identifier == "class"
        || identifier == "const"
        || identifier == "continue"
        || identifier == "default"
        || identifier == "do"
        || identifier == "double"
        || identifier == "else"
        || identifier == "enum" // probable addition in Java 1.5
        || identifier == "extends"
        || identifier == "final"
        || identifier == "finally"
        || identifier == "float"
        || identifier == "for"
        || identifier == "goto"
        || identifier == "if"
        || identifier == "implements"
        || identifier == "import"
        || identifier == "instanceof"
        || identifier == "int"
        || identifier == "interface"
        || identifier == "long"
        || identifier == "native"
        || identifier == "new"
        || identifier == "package"
        || identifier == "private"
        || identifier == "protected"
        || identifier == "public"
        || identifier == "return"
        || identifier == "short"
        || identifier == "static"
        || identifier == "strictfp"
        || identifier == "super"
        || identifier == "switch"
        || identifier == "synchronized"
        || identifier == "this"
        || identifier == "throw"
        || identifier == "throws"
        || identifier == "transient"
        || identifier == "try"
        || identifier == "void"
        || identifier == "volatile"
        || identifier == "while")
    {
        rtl::OStringBuffer buf(prefix);
        buf.append('_');
        buf.append(identifier);
        return buf.makeStringAndClear();
    } else {
        return identifier;
    }
}

} }
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.10); FILE MERGED 2005/09/05 17:27:59 rt 1.2.10.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: commonjava.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:11:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "sal/config.h"

#include "codemaker/commonjava.hxx"

#include "codemaker/options.hxx"
#include "codemaker/typemanager.hxx"
#include "codemaker/unotype.hxx"

#include "osl/diagnose.h"
#include "registry/reader.hxx"
#include "registry/types.h"
#include "rtl/strbuf.h"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"

#include <vector>

namespace codemaker { namespace java {

rtl::OString translateUnoToJavaType(
    codemaker::UnoType::Sort sort, RTTypeClass typeClass,
    rtl::OString const & nucleus, bool referenceType)
{
    rtl::OStringBuffer buf;
    if (sort == codemaker::UnoType::SORT_COMPLEX) {
        if (typeClass == RT_TYPE_INTERFACE
            && nucleus == rtl::OString("com/sun/star/uno/XInterface"))
        {
            buf.append(RTL_CONSTASCII_STRINGPARAM("java/lang/Object"));
        } else {
            //TODO: check that nucleus is a valid (Java-modified UTF-8)
            // identifier
            buf.append(nucleus);
        }
    } else {
        rtl::OString const javaTypes[codemaker::UnoType::SORT_ANY + 1][2] = {
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("void")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Void")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("boolean")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Boolean")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("byte")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Byte")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("short")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Short")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("short")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Short")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("int")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Integer")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("int")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Integer")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("long")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Long")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("long")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Long")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("float")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Float")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("double")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Double")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("char")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Character")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/String")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/String")) },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("com/sun/star/uno/Type")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("com/sun/star/uno/Type"))
            },
            { rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Object")),
              rtl::OString(RTL_CONSTASCII_STRINGPARAM("java/lang/Object")) } };
        buf.append(javaTypes[sort][referenceType]);
    }
    return buf.makeStringAndClear();
}

rtl::OString translateUnoToJavaIdentifier(
    rtl::OString const & identifier, rtl::OString const & prefix)
{
    if (identifier == "abstract"
        || identifier == "assert" // since Java 1.4
        || identifier == "boolean"
        || identifier == "break"
        || identifier == "byte"
        || identifier == "case"
        || identifier == "catch"
        || identifier == "char"
        || identifier == "class"
        || identifier == "const"
        || identifier == "continue"
        || identifier == "default"
        || identifier == "do"
        || identifier == "double"
        || identifier == "else"
        || identifier == "enum" // probable addition in Java 1.5
        || identifier == "extends"
        || identifier == "final"
        || identifier == "finally"
        || identifier == "float"
        || identifier == "for"
        || identifier == "goto"
        || identifier == "if"
        || identifier == "implements"
        || identifier == "import"
        || identifier == "instanceof"
        || identifier == "int"
        || identifier == "interface"
        || identifier == "long"
        || identifier == "native"
        || identifier == "new"
        || identifier == "package"
        || identifier == "private"
        || identifier == "protected"
        || identifier == "public"
        || identifier == "return"
        || identifier == "short"
        || identifier == "static"
        || identifier == "strictfp"
        || identifier == "super"
        || identifier == "switch"
        || identifier == "synchronized"
        || identifier == "this"
        || identifier == "throw"
        || identifier == "throws"
        || identifier == "transient"
        || identifier == "try"
        || identifier == "void"
        || identifier == "volatile"
        || identifier == "while")
    {
        rtl::OStringBuffer buf(prefix);
        buf.append('_');
        buf.append(identifier);
        return buf.makeStringAndClear();
    } else {
        return identifier;
    }
}

} }
<|endoftext|>


<commit_before>/******************************************************************************
 * @file     hgpu_prng_test.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.1
 *
 * @brief    [PRNGCL library]
 *           Pseudo-random number generators for HGPU package
 *           tests submodule
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2013, Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/

#include "hgpu_prng.h"

unsigned int
HGPU_PRNG_tests(HGPU_GPU_context* context){
    unsigned int result = 0;

    // Toy PRNGs:
    result += HGPU_PRNG_test(context,HGPU_PRNG_PM,      1,HGPU_precision_single,10000,0.8641089363322169);
    result += HGPU_PRNG_test(context,HGPU_PRNG_CONSTANT,1,HGPU_precision_single,10000,0.0234896258916706);

    result += HGPU_PRNG_test(context,HGPU_PRNG_XOR128,  1,HGPU_precision_single,1000000,0.6839658189564943);
    result += HGPU_PRNG_test(context,HGPU_PRNG_XOR7,    1,HGPU_precision_single,1000000,0.09432704793289304);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANECU,  1,HGPU_precision_single,1000000,0.1810733857564628);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANMAR,  1,HGPU_precision_single,1000000,0.9911311864852905);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANLUX,  1,HGPU_precision_single,1000000,0.42132478952407837);
    result += HGPU_PRNG_test(context,HGPU_PRNG_MRG32K3A,1,HGPU_precision_single,1000000,0.8171486894057429);

    // Toy PRNGs:
    result += HGPU_PRNG_test(context,HGPU_PRNG_CONSTANT,1,HGPU_precision_double,1000000,0.023489625891670585);

    result += HGPU_PRNG_test(context,HGPU_PRNG_XOR128,  1,HGPU_precision_double,1000000,0.75871549689209505);
    result += HGPU_PRNG_test(context,HGPU_PRNG_XOR7,    1,HGPU_precision_double,1000000,0.75934357677468545);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANECU,  1,HGPU_precision_double,1000000,0.31995889215386432);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANMAR,  1,HGPU_precision_double,1000000,0.6419413344753124);
    result += HGPU_PRNG_test(context,HGPU_PRNG_RANLUX,  1,HGPU_precision_double,1000000,0.9564072613718381);
    result += HGPU_PRNG_test(context,HGPU_PRNG_MRG32K3A,1,HGPU_precision_double,1000000,0.00755252070810589);

    printf(" **************************************************\n");
    if (result)
        printf(" %u test(s) failed!!!\n",result);
    else
        printf(" All tests passed\n");
    printf(" **************************************************\n");

    return result;
}

void
HGPU_PRNG_benchmarks(HGPU_GPU_context* context){
    double result = 0.0;

    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_CONSTANT,HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_PM,      HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR128,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR7,    HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANECU,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANMAR,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANLUX,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_MRG32K3A,HGPU_precision_single);

    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_CONSTANT,HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_PM,      HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR128,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_XOR7,    HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANECU,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANMAR,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_RANLUX,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,HGPU_PRNG_MRG32K3A,HGPU_precision_double);

}
<commit_msg>tests submodule<commit_after>/******************************************************************************
 * @file     hgpu_prng_test.cpp
 * @author   Vadim Demchik <vadimdi@yahoo.com>
 * @version  1.1.1
 *
 * @brief    [PRNGCL library]
 *           Pseudo-random number generators for HGPU package
 *           tests submodule
 *
 *
 * @section  LICENSE
 *
 * Copyright (c) 2013, 2014 Vadim Demchik
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *****************************************************************************/

#include "hgpu_prng.h"

unsigned int
HGPU_PRNG_tests(HGPU_GPU_context* context,HGPU_parameter** parameters){
    unsigned int result = 0;

    // Toy PRNGs:
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_PM,      1,HGPU_precision_single,10000,0.8641089363322169);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_CONSTANT,1,HGPU_precision_single,10000,0.0234896258916706);

    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_XOR128,  1,HGPU_precision_single,1000000,0.6839658189564943);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_XOR7,    1,HGPU_precision_single,1000000,0.09432704793289304);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANECU,  1,HGPU_precision_single,1000000,0.1810733857564628);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANMAR,  1,HGPU_precision_single,1000000,0.9911311864852905);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANLUX,  1,HGPU_precision_single,1000000,0.42132478952407837);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_MRG32K3A,1,HGPU_precision_single,1000000,0.8171486894057429);

    // Toy PRNGs:
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_PM,      1,HGPU_precision_double,1000000,0.330385444271241);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_CONSTANT,1,HGPU_precision_double,1000000,0.023489625891670585);

    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_XOR128,  1,HGPU_precision_double,1000000,0.75871549689209505);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_XOR7,    1,HGPU_precision_double,1000000,0.75934357677468545);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANECU,  1,HGPU_precision_double,1000000,0.31995889215386432);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANMAR,  1,HGPU_precision_double,1000000,0.6419413344753121);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_RANLUX,  1,HGPU_precision_double,1000000,0.95640726137184218);
    result += HGPU_PRNG_test(context,parameters,HGPU_PRNG_MRG32K3A,1,HGPU_precision_double,1000000,0.0075525209409365449);

    printf(" **************************************************\n");
    if (result)
        printf(" %u test(s) failed!!!\n",result);
    else
        printf(" All tests passed\n");
    printf(" **************************************************\n");

    return result;
}

void
HGPU_PRNG_benchmarks(HGPU_GPU_context* context,HGPU_parameter** parameters){
    double result = 0.0;

    char* timestamp = HGPU_timer_get_current_datetime();
        printf("\nStarted at: %s (%u tics/sec)\n\n",timestamp,(unsigned int) CLOCKS_PER_SEC);
    free(timestamp);

    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_CONSTANT,HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_PM,      HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_XOR128,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_XOR7,    HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANECU,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANMAR,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANLUX,  HGPU_precision_single);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_MRG32K3A,HGPU_precision_single);

    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_CONSTANT,HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_PM,      HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_XOR128,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_XOR7,    HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANECU,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANMAR,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_RANLUX,  HGPU_precision_double);
    result += HGPU_PRNG_benchmark(context,parameters,HGPU_PRNG_MRG32K3A,HGPU_precision_double);

    timestamp = HGPU_timer_get_current_datetime();
        printf("\nFinished at: %s\n",timestamp);
    free(timestamp);

}
<|endoftext|>