<commit_before>#include <string>
#include <stdexcept>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <sauce/sauce.h>

using ::testing::Sequence;
using ::testing::Return;

using ::sauce::Binder;
using ::sauce::Named;

namespace sauce {
namespace test {

class Bound {};

void BoundModule(Binder & binder) {
  binder.bind<Bound>().to<Bound()>();
}

TEST(BindingTest, shouldProvideBoundDependenciesAndTheirProvidersToo) {
  sauce::shared_ptr<Injector> injector(Modules().add(&BoundModule).createInjector());

  // We can get an instance, or a provider
  sauce::shared_ptr<Bound> explicitlyBound = injector->get<Bound>();
  sauce::shared_ptr<Provider<Bound> > provider = injector->get<Provider<Bound> >();
}

void ForgotTheParensModule(Binder & binder) {
  binder.bind<Bound>().to<Bound>();
}

TEST(BindingTest, shouldInterpretNonFunctionTypesAsNoArgumentConstructors) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ForgotTheParensModule).createInjector());

  sauce::shared_ptr<Bound> bound = injector->get<Bound>();
  sauce::shared_ptr<Provider<Bound> > provider = injector->get<Provider<Bound> >();
}

class PureVirtual {
public:
  virtual std::string says() = 0;
};

class PureVirtualImpl: public PureVirtual {
public:
  std::string says() {
    return "impl!";
  }
};

class NeedsPureVirtual {
public:
  sauce::shared_ptr<PureVirtual> pure;
  explicit NeedsPureVirtual(sauce::shared_ptr<PureVirtual> pure):
    pure(pure) {}
};

void UnnamedPureVirtualModule(Binder & binder) {
  binder.bind<PureVirtual>().to<PureVirtualImpl()>();
  binder.bind<NeedsPureVirtual>().to<NeedsPureVirtual(PureVirtual &)>();
}

/**
 * Ensure a work-around exists for a wart I introduce while abusing syntax.
 *
 * Sauce uses virtually no macros.  So, the injected signatures such as
 * NeedsPureVirtual(PureVirtual &) above are actual language objects.  Specifically they are
 * function types.  However, some function types are illegal, such as those that pass by value
 * uncopyable objects (such as instances of a pure virutal interface by value.)
 *
 * Notice this only affects unnamed dependencies, since the Named<> type wrapper otherwise
 * protects us.
 *
 * Sauce doesn't really care too much about the types of injected dependencies in this sense,
 * since it's going to actually pass in everything as smart pointers anyway.  The choice of using
 * bare types is a convenience to the user, to keep bindings as uncluttered as possible.
 *
 * Therefore, let's abuse the system a little further.  Anywhere an injected type is needed, it
 * can named either as itself, or as a reference to itself (as in PureVirtual & above).  If Sauce
 * sees any reference types in this way, it will simply pull the reference modifier off (via a
 * certain template specialization) and treat it as if the & was never there.
 *
 * I don't feel guilty about this altering of the space of possible bound types, since (smart)
 * pointers to reference types are illegal anyway.
 */
TEST(BindingTest, shouldAllowBindingUnnamedPureVirtualDependenciesByReference) {
  sauce::shared_ptr<Injector> injector(Modules().add(&UnnamedPureVirtualModule).createInjector());
  EXPECT_EQ("impl!", (injector->get<NeedsPureVirtual>()->pure->says()));
}

class CustomBuilt {};

class CustomBuiltProvider: public AbstractProvider<CustomBuilt> {
public:
  CustomBuilt * provide() {
    return new CustomBuilt();
  }

  void dispose(CustomBuilt * customBuilt) {
    delete customBuilt;
  }
};

void ProviderModule(Binder & binder) {
  binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider()>();
}

TEST(BindingTest, shouldProvideDependenciesBoundToProvidersAndTheProvidersToo) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ProviderModule).createInjector());

  // We can get an instance, or a provider
  sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
  sauce::shared_ptr<Provider<CustomBuilt> > provider = injector->get<Provider<CustomBuilt> >();
}

void ForgotTheParensProviderModule(Binder & binder) {
  binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider>();
}

TEST(BindingTest, shouldInterpretNonFunctionProviderTypesAsNoArgumentProviderConstructors) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ForgotTheParensProviderModule).createInjector());

  sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
  sauce::shared_ptr<Provider<CustomBuilt> > customBuiltProvider = injector->get<Provider<CustomBuilt> >();
  sauce::shared_ptr<CustomBuilt> explicitlyProvided = customBuiltProvider->get();
}

class Unbound {};

TEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
  sauce::shared_ptr<Injector> injector(Modules().createInjector());
  ASSERT_THROW(injector->get<Unbound>(), ::sauce::UnboundException);
}

TEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {
  sauce::shared_ptr<Injector> expected = Modules().createInjector();
  sauce::shared_ptr<Injector> actual = expected->get<Injector>();
  ASSERT_EQ(expected, actual);
}

class HasSetter {
public:
  sauce::shared_ptr<Bound> bound;

  HasSetter():
    bound() {}

  void setBound(sauce::shared_ptr<Bound> bound) {
    this->bound = bound;
  }

  sauce::shared_ptr<Bound> getBound() {
    return bound;
  }
};

void SetterModule(Binder & binder) {
  binder.bind<Bound>().in<SingletonScope>().to<Bound()>();
  binder.bind<HasSetter>().toMethod(&HasSetter::setBound);
}

TEST(BindingTest, shouldInjectBoundSettersOnUserSuppliedValues) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SetterModule).createInjector());

  sauce::shared_ptr<HasSetter> hasSetter(new HasSetter());
  // injector->inject<HasSetter>(hasSetter);

  sauce::shared_ptr<Bound> bound = injector->get<Bound>();
  // Equal since Bound is a singleton
  // ASSERT_EQ(bound, hasSetter->getBound()); // TODO
}

class Dog;

class Tail {
public:
  Tail(sauce::shared_ptr<Dog>) {}
};

class Dog {
public:
  Dog(sauce::shared_ptr<Tail>) {}
};

void CircularModule(Binder & binder) {
  binder.bind<Tail>().in<SingletonScope>().to<Tail(Dog)>();
  binder.bind<Dog>().in<SingletonScope>().to<Dog(Tail)>();
}

TEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
  ASSERT_THROW(injector->get<Tail>(), ::sauce::CircularDependencyException);
}

TEST(BindingTest, shouldThrowExceptionWhenEagerlyInjectingCircularDependency) {
  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
  ASSERT_THROW(injector->eagerlyInject<SingletonScope>(), ::sauce::CircularDependencyException);
}

class IncompletelyBound {};

void IncompleteModule(Binder & binder) {
  binder.bind<IncompletelyBound>() /* to ...? */;
}

TEST(BindingTest, shouldThrowExceptionOnPartialBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteModule).createInjector(),
    ::sauce::PartialBindingException);
}

class Animal {
public:
  virtual std::string says() = 0;
};

class Cat: public Animal {
public:
  std::string says() { return "Meow"; }
};

class LieutenantShinysides {};
class Fish: public Animal {
public:
  std::string says() { return "Blub blub"; }
};

class Meatloaf {};
class Cow: public Animal {
public:
  std::string says() { return "Moo"; }
};

class CowProvider: public AbstractProvider<Animal> {
public:
  Animal * provide() {
    return new Cow();
  }

  void dispose(Animal * cow) {
    delete cow;
  }
};

class Bird: public Animal {
public:
  std::string says() { return "Cheep cheep"; }
};

class Pond {
public:
  sauce::shared_ptr<Animal> animal;

  Pond(sauce::shared_ptr<Animal> animal):
    animal(animal) {}
};

class BirdCage {
public:
  sauce::shared_ptr<Animal> animal;

  BirdCage(sauce::shared_ptr<Animal> animal):
    animal(animal) {}
};

void AnimalModule(Binder & binder) {
  binder.bind<Animal>().to<Cat()>();
  binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>();
  binder.bind<Animal>().named<Meatloaf>().toProvider<CowProvider()>();
  binder.bind<Animal>().named("tweety").to<Bird()>();

  binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>();
  binder.bind<BirdCage>().to<BirdCage(Animal &)>().naming(0, "tweety");
}

TEST(BindingTest, shouldProvidedNamedDependencies) {
  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());

  EXPECT_EQ("Meow",         (injector->get<Animal>()->says()));
  EXPECT_EQ("Blub blub",    (injector->get<Animal, LieutenantShinysides>()->says()));
  EXPECT_EQ("Moo",          (injector->get<Named<Animal, Meatloaf> >()->says()));
  EXPECT_EQ("Cheep cheep",  (injector->get<Animal>("tweety")->says()));

  EXPECT_EQ("Blub blub",    (injector->get<Pond>()->animal->says()));
  EXPECT_EQ("Cheep cheep",  (injector->get<BirdCage>()->animal->says()));
}

TEST(BindingTest, shouldProvidedNamedDependencyProviders) {
  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());

  sauce::shared_ptr<Provider<Animal> > animalProvider = injector->get<Provider<Animal> >();
  EXPECT_EQ("Meow", animalProvider->get()->says());

  sauce::shared_ptr<Provider<Named<Animal, LieutenantShinysides> > > namedImplicitProvider =
    injector->get<Provider<Named<Animal, LieutenantShinysides> > >();
  EXPECT_EQ("Blub blub", namedImplicitProvider->get()->says());

  sauce::shared_ptr<Provider<Named<Animal, Meatloaf> > > namedExplicitProvider =
    injector->get<Provider<Named<Animal, Meatloaf> > >();
  EXPECT_EQ("Moo", namedExplicitProvider->get()->says());

  sauce::shared_ptr<Provider<Animal> > dynamicallyNamedProvider =
    injector->get<Provider<Animal> >("tweety");
  EXPECT_EQ("Cheep cheep", dynamicallyNamedProvider->get()->says());
}

void BirdDynamicModule(Binder & binder) {
  binder.bind<Animal>().named("tweety").to<Bird()>();
}

void CatDynamicModule(Binder & binder) {
  binder.bind<Animal>().named("sylvester").to<Cat()>();
}

TEST(BindingTest, shouldProvidedDynamicallyNamedDependenciesAcrossModules) {
  Modules modules;
  modules.add(&BirdDynamicModule).add(&CatDynamicModule);
  sauce::shared_ptr<Injector> injector(modules.createInjector());

  EXPECT_EQ("Cheep cheep", (injector->get<Animal>("tweety")->says()));
  EXPECT_EQ("Meow", (injector->get<Animal>("sylvester")->says()));
}

void DynamicallyNamedBindingWithADependencyModule(Binder & binder) {
  binder.bind<Animal>().to<Bird()>();
  binder.bind<BirdCage>().named("golden").to<BirdCage(Animal &)>();
}

TEST(BindingTest, shouldProvideDynamicallyNamedRequestsThatHaveDependencies) {
  Modules modules;
  modules.add(&DynamicallyNamedBindingWithADependencyModule);
  sauce::shared_ptr<Injector> injector(modules.createInjector());

  // This does *not* throw UnboundException (this is a regression test.)
  injector->get<BirdCage>("golden");
}

void IncompleteNamedModule(Binder & binder) {
  binder.bind<IncompletelyBound>().named<LieutenantShinysides>() /* to ...? */;
}

TEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteNamedModule).createInjector(),
    ::sauce::PartialBindingException);
}

void IncompleteScopeModule(Binder & binder) {
  binder.bind<IncompletelyBound>().in<SingletonScope>();
}

TEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteScopeModule).createInjector(),
    ::sauce::PartialBindingException);
}

class SelfInterested: public Bound {
public:
  sauce::weak_ptr<SelfInterested> self;

  SelfInterested():
    self() {}

  /**
   * The existence of this typedef indicates SelfInterested wants a self-pointer injected.
   */
  typedef SelfInterested RequestsSelfInjection;

  /**
   * This is the setter that the self-pointer is injected with.
   *
   * If the typedef exists but the setter does not, it is a compile error.
   *
   * Notice the weak_ptr is over the type idenfied by RequestsSelfInjection.
   */
  void setSelf(sauce::weak_ptr<SelfInterested> self) {
    this->self = self;
  }
};

class SonOfSelfInterested: public SelfInterested {};

void SelfInterestedModule(Binder & binder) {
  binder.bind<SelfInterested>().to<SelfInterested>();
  binder.bind<SonOfSelfInterested>().to<SonOfSelfInterested>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersIfSpecialTypedefExists) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedModule).createInjector());
  sauce::shared_ptr<SelfInterested> selfInterested = injector->get<SelfInterested>();
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

TEST(BindingTest, shouldInjectSelfWeakPointersAutomaticallyIfSpecialTypedefIsInherited) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedModule).createInjector());
  sauce::shared_ptr<SonOfSelfInterested> son = injector->get<SonOfSelfInterested>();
  ASSERT_EQ(son, son->self.lock());
}

class SelfInterestedProvider: public AbstractProvider<SelfInterested> {
public:
  SelfInterested * provide() {
    return new SelfInterested();
  }

  void dispose(SelfInterested * selfInterested) {
    delete selfInterested;
  }
};

void SelfInterestedProviderModule(Binder & binder) {
  binder.bind<SelfInterested>().toProvider<SelfInterestedProvider()>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersFromProviders) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedProviderModule).createInjector());
  sauce::shared_ptr<SelfInterested> selfInterested = injector->get<SelfInterested>();
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

void SecretlySelfInterestedModule(Binder & binder) {
  binder.bind<Bound>().to<SelfInterested>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersIfOnlyOnConcreteTypeKnownToBinding) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SecretlySelfInterestedModule).createInjector());
  sauce::shared_ptr<Bound> secretlySelfInterested = injector->get<Bound>();
  sauce::shared_ptr<SelfInterested> selfInterested = static_pointer_cast<SelfInterested>(secretlySelfInterested);
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

}
}
<commit_msg>Call Injector::inject in test, without throwing.<commit_after>#include <string>
#include <stdexcept>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <sauce/sauce.h>

using ::testing::Sequence;
using ::testing::Return;

using ::sauce::Binder;
using ::sauce::Named;

namespace sauce {
namespace test {

class Bound {};

void BoundModule(Binder & binder) {
  binder.bind<Bound>().to<Bound()>();
}

TEST(BindingTest, shouldProvideBoundDependenciesAndTheirProvidersToo) {
  sauce::shared_ptr<Injector> injector(Modules().add(&BoundModule).createInjector());

  // We can get an instance, or a provider
  sauce::shared_ptr<Bound> explicitlyBound = injector->get<Bound>();
  sauce::shared_ptr<Provider<Bound> > provider = injector->get<Provider<Bound> >();
}

void ForgotTheParensModule(Binder & binder) {
  binder.bind<Bound>().to<Bound>();
}

TEST(BindingTest, shouldInterpretNonFunctionTypesAsNoArgumentConstructors) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ForgotTheParensModule).createInjector());

  sauce::shared_ptr<Bound> bound = injector->get<Bound>();
  sauce::shared_ptr<Provider<Bound> > provider = injector->get<Provider<Bound> >();
}

class PureVirtual {
public:
  virtual std::string says() = 0;
};

class PureVirtualImpl: public PureVirtual {
public:
  std::string says() {
    return "impl!";
  }
};

class NeedsPureVirtual {
public:
  sauce::shared_ptr<PureVirtual> pure;
  explicit NeedsPureVirtual(sauce::shared_ptr<PureVirtual> pure):
    pure(pure) {}
};

void UnnamedPureVirtualModule(Binder & binder) {
  binder.bind<PureVirtual>().to<PureVirtualImpl()>();
  binder.bind<NeedsPureVirtual>().to<NeedsPureVirtual(PureVirtual &)>();
}

/**
 * Ensure a work-around exists for a wart I introduce while abusing syntax.
 *
 * Sauce uses virtually no macros.  So, the injected signatures such as
 * NeedsPureVirtual(PureVirtual &) above are actual language objects.  Specifically they are
 * function types.  However, some function types are illegal, such as those that pass by value
 * uncopyable objects (such as instances of a pure virutal interface by value.)
 *
 * Notice this only affects unnamed dependencies, since the Named<> type wrapper otherwise
 * protects us.
 *
 * Sauce doesn't really care too much about the types of injected dependencies in this sense,
 * since it's going to actually pass in everything as smart pointers anyway.  The choice of using
 * bare types is a convenience to the user, to keep bindings as uncluttered as possible.
 *
 * Therefore, let's abuse the system a little further.  Anywhere an injected type is needed, it
 * can named either as itself, or as a reference to itself (as in PureVirtual & above).  If Sauce
 * sees any reference types in this way, it will simply pull the reference modifier off (via a
 * certain template specialization) and treat it as if the & was never there.
 *
 * I don't feel guilty about this altering of the space of possible bound types, since (smart)
 * pointers to reference types are illegal anyway.
 */
TEST(BindingTest, shouldAllowBindingUnnamedPureVirtualDependenciesByReference) {
  sauce::shared_ptr<Injector> injector(Modules().add(&UnnamedPureVirtualModule).createInjector());
  EXPECT_EQ("impl!", (injector->get<NeedsPureVirtual>()->pure->says()));
}

class CustomBuilt {};

class CustomBuiltProvider: public AbstractProvider<CustomBuilt> {
public:
  CustomBuilt * provide() {
    return new CustomBuilt();
  }

  void dispose(CustomBuilt * customBuilt) {
    delete customBuilt;
  }
};

void ProviderModule(Binder & binder) {
  binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider()>();
}

TEST(BindingTest, shouldProvideDependenciesBoundToProvidersAndTheProvidersToo) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ProviderModule).createInjector());

  // We can get an instance, or a provider
  sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
  sauce::shared_ptr<Provider<CustomBuilt> > provider = injector->get<Provider<CustomBuilt> >();
}

void ForgotTheParensProviderModule(Binder & binder) {
  binder.bind<CustomBuilt>().toProvider<CustomBuiltProvider>();
}

TEST(BindingTest, shouldInterpretNonFunctionProviderTypesAsNoArgumentProviderConstructors) {
  sauce::shared_ptr<Injector> injector(Modules().add(&ForgotTheParensProviderModule).createInjector());

  sauce::shared_ptr<CustomBuilt> customBuilt = injector->get<CustomBuilt>();
  sauce::shared_ptr<Provider<CustomBuilt> > customBuiltProvider = injector->get<Provider<CustomBuilt> >();
  sauce::shared_ptr<CustomBuilt> explicitlyProvided = customBuiltProvider->get();
}

class Unbound {};

TEST(BindingTest, shouldThrowExceptionWhenGettingAnUnboundIface) {
  sauce::shared_ptr<Injector> injector(Modules().createInjector());
  ASSERT_THROW(injector->get<Unbound>(), ::sauce::UnboundException);
}

TEST(BindingTest, shouldImplicitlyBindTheInjectorItself) {
  sauce::shared_ptr<Injector> expected = Modules().createInjector();
  sauce::shared_ptr<Injector> actual = expected->get<Injector>();
  ASSERT_EQ(expected, actual);
}

class HasSetter {
public:
  sauce::shared_ptr<Bound> bound;

  HasSetter():
    bound() {}

  void setBound(sauce::shared_ptr<Bound> bound) {
    this->bound = bound;
  }

  sauce::shared_ptr<Bound> getBound() {
    return bound;
  }
};

void SetterModule(Binder & binder) {
  binder.bind<Bound>().in<SingletonScope>().to<Bound()>();
  binder.bind<HasSetter>().toMethod(&HasSetter::setBound);
}

TEST(BindingTest, shouldInjectBoundSettersOnUserSuppliedValues) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SetterModule).createInjector());

  sauce::shared_ptr<HasSetter> hasSetter(new HasSetter());
  injector->inject<HasSetter>(hasSetter);

  sauce::shared_ptr<Bound> bound = injector->get<Bound>();
  // Equal since Bound is a singleton
  // ASSERT_EQ(bound, hasSetter->getBound()); // TODO
}

class Dog;

class Tail {
public:
  Tail(sauce::shared_ptr<Dog>) {}
};

class Dog {
public:
  Dog(sauce::shared_ptr<Tail>) {}
};

void CircularModule(Binder & binder) {
  binder.bind<Tail>().in<SingletonScope>().to<Tail(Dog)>();
  binder.bind<Dog>().in<SingletonScope>().to<Dog(Tail)>();
}

TEST(BindingTest, shouldThrowExceptionWhenResolvingCircularDependency) {
  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
  ASSERT_THROW(injector->get<Tail>(), ::sauce::CircularDependencyException);
}

TEST(BindingTest, shouldThrowExceptionWhenEagerlyInjectingCircularDependency) {
  sauce::shared_ptr<Injector> injector(Modules().add(&CircularModule).createInjector());
  ASSERT_THROW(injector->eagerlyInject<SingletonScope>(), ::sauce::CircularDependencyException);
}

class IncompletelyBound {};

void IncompleteModule(Binder & binder) {
  binder.bind<IncompletelyBound>() /* to ...? */;
}

TEST(BindingTest, shouldThrowExceptionOnPartialBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteModule).createInjector(),
    ::sauce::PartialBindingException);
}

class Animal {
public:
  virtual std::string says() = 0;
};

class Cat: public Animal {
public:
  std::string says() { return "Meow"; }
};

class LieutenantShinysides {};
class Fish: public Animal {
public:
  std::string says() { return "Blub blub"; }
};

class Meatloaf {};
class Cow: public Animal {
public:
  std::string says() { return "Moo"; }
};

class CowProvider: public AbstractProvider<Animal> {
public:
  Animal * provide() {
    return new Cow();
  }

  void dispose(Animal * cow) {
    delete cow;
  }
};

class Bird: public Animal {
public:
  std::string says() { return "Cheep cheep"; }
};

class Pond {
public:
  sauce::shared_ptr<Animal> animal;

  Pond(sauce::shared_ptr<Animal> animal):
    animal(animal) {}
};

class BirdCage {
public:
  sauce::shared_ptr<Animal> animal;

  BirdCage(sauce::shared_ptr<Animal> animal):
    animal(animal) {}
};

void AnimalModule(Binder & binder) {
  binder.bind<Animal>().to<Cat()>();
  binder.bind<Animal>().named<LieutenantShinysides>().to<Fish()>();
  binder.bind<Animal>().named<Meatloaf>().toProvider<CowProvider()>();
  binder.bind<Animal>().named("tweety").to<Bird()>();

  binder.bind<Pond>().to<Pond(Named<Animal, LieutenantShinysides>)>();
  binder.bind<BirdCage>().to<BirdCage(Animal &)>().naming(0, "tweety");
}

TEST(BindingTest, shouldProvidedNamedDependencies) {
  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());

  EXPECT_EQ("Meow",         (injector->get<Animal>()->says()));
  EXPECT_EQ("Blub blub",    (injector->get<Animal, LieutenantShinysides>()->says()));
  EXPECT_EQ("Moo",          (injector->get<Named<Animal, Meatloaf> >()->says()));
  EXPECT_EQ("Cheep cheep",  (injector->get<Animal>("tweety")->says()));

  EXPECT_EQ("Blub blub",    (injector->get<Pond>()->animal->says()));
  EXPECT_EQ("Cheep cheep",  (injector->get<BirdCage>()->animal->says()));
}

TEST(BindingTest, shouldProvidedNamedDependencyProviders) {
  sauce::shared_ptr<Injector> injector(Modules().add(&AnimalModule).createInjector());

  sauce::shared_ptr<Provider<Animal> > animalProvider = injector->get<Provider<Animal> >();
  EXPECT_EQ("Meow", animalProvider->get()->says());

  sauce::shared_ptr<Provider<Named<Animal, LieutenantShinysides> > > namedImplicitProvider =
    injector->get<Provider<Named<Animal, LieutenantShinysides> > >();
  EXPECT_EQ("Blub blub", namedImplicitProvider->get()->says());

  sauce::shared_ptr<Provider<Named<Animal, Meatloaf> > > namedExplicitProvider =
    injector->get<Provider<Named<Animal, Meatloaf> > >();
  EXPECT_EQ("Moo", namedExplicitProvider->get()->says());

  sauce::shared_ptr<Provider<Animal> > dynamicallyNamedProvider =
    injector->get<Provider<Animal> >("tweety");
  EXPECT_EQ("Cheep cheep", dynamicallyNamedProvider->get()->says());
}

void BirdDynamicModule(Binder & binder) {
  binder.bind<Animal>().named("tweety").to<Bird()>();
}

void CatDynamicModule(Binder & binder) {
  binder.bind<Animal>().named("sylvester").to<Cat()>();
}

TEST(BindingTest, shouldProvidedDynamicallyNamedDependenciesAcrossModules) {
  Modules modules;
  modules.add(&BirdDynamicModule).add(&CatDynamicModule);
  sauce::shared_ptr<Injector> injector(modules.createInjector());

  EXPECT_EQ("Cheep cheep", (injector->get<Animal>("tweety")->says()));
  EXPECT_EQ("Meow", (injector->get<Animal>("sylvester")->says()));
}

void DynamicallyNamedBindingWithADependencyModule(Binder & binder) {
  binder.bind<Animal>().to<Bird()>();
  binder.bind<BirdCage>().named("golden").to<BirdCage(Animal &)>();
}

TEST(BindingTest, shouldProvideDynamicallyNamedRequestsThatHaveDependencies) {
  Modules modules;
  modules.add(&DynamicallyNamedBindingWithADependencyModule);
  sauce::shared_ptr<Injector> injector(modules.createInjector());

  // This does *not* throw UnboundException (this is a regression test.)
  injector->get<BirdCage>("golden");
}

void IncompleteNamedModule(Binder & binder) {
  binder.bind<IncompletelyBound>().named<LieutenantShinysides>() /* to ...? */;
}

TEST(BindingTest, shouldThrowExceptionOnPartialNamedBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteNamedModule).createInjector(),
    ::sauce::PartialBindingException);
}

void IncompleteScopeModule(Binder & binder) {
  binder.bind<IncompletelyBound>().in<SingletonScope>();
}

TEST(BindingTest, shouldThrowExceptionOnPartialScopedBinding) {
  ASSERT_THROW(
    Modules().add(&IncompleteScopeModule).createInjector(),
    ::sauce::PartialBindingException);
}

class SelfInterested: public Bound {
public:
  sauce::weak_ptr<SelfInterested> self;

  SelfInterested():
    self() {}

  /**
   * The existence of this typedef indicates SelfInterested wants a self-pointer injected.
   */
  typedef SelfInterested RequestsSelfInjection;

  /**
   * This is the setter that the self-pointer is injected with.
   *
   * If the typedef exists but the setter does not, it is a compile error.
   *
   * Notice the weak_ptr is over the type idenfied by RequestsSelfInjection.
   */
  void setSelf(sauce::weak_ptr<SelfInterested> self) {
    this->self = self;
  }
};

class SonOfSelfInterested: public SelfInterested {};

void SelfInterestedModule(Binder & binder) {
  binder.bind<SelfInterested>().to<SelfInterested>();
  binder.bind<SonOfSelfInterested>().to<SonOfSelfInterested>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersIfSpecialTypedefExists) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedModule).createInjector());
  sauce::shared_ptr<SelfInterested> selfInterested = injector->get<SelfInterested>();
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

TEST(BindingTest, shouldInjectSelfWeakPointersAutomaticallyIfSpecialTypedefIsInherited) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedModule).createInjector());
  sauce::shared_ptr<SonOfSelfInterested> son = injector->get<SonOfSelfInterested>();
  ASSERT_EQ(son, son->self.lock());
}

class SelfInterestedProvider: public AbstractProvider<SelfInterested> {
public:
  SelfInterested * provide() {
    return new SelfInterested();
  }

  void dispose(SelfInterested * selfInterested) {
    delete selfInterested;
  }
};

void SelfInterestedProviderModule(Binder & binder) {
  binder.bind<SelfInterested>().toProvider<SelfInterestedProvider()>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersFromProviders) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SelfInterestedProviderModule).createInjector());
  sauce::shared_ptr<SelfInterested> selfInterested = injector->get<SelfInterested>();
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

void SecretlySelfInterestedModule(Binder & binder) {
  binder.bind<Bound>().to<SelfInterested>();
}

TEST(BindingTest, shouldInjectSelfWeakPointersIfOnlyOnConcreteTypeKnownToBinding) {
  sauce::shared_ptr<Injector> injector(Modules().add(&SecretlySelfInterestedModule).createInjector());
  sauce::shared_ptr<Bound> secretlySelfInterested = injector->get<Bound>();
  sauce::shared_ptr<SelfInterested> selfInterested = static_pointer_cast<SelfInterested>(secretlySelfInterested);
  ASSERT_EQ(selfInterested, selfInterested->self.lock());
}

}
}
<|endoftext|>


<commit_before>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "catch.hpp"

#include <xsd++/extern.h> /* for xsd_*_*() */

#include <cerrno>         /* for E*, errno */
#include <cmath>          /* for std::isinf(), std::isnan() */

////////////////////////////////////////////////////////////////////////////////
/* xsd:base64Binary */

TEST_CASE("xsd_base64_validate()") {
  //REQUIRE(xsd_base64_validate("") == false); // FIXME
  // TODO
}

TEST_CASE("xsd_base64_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_base64_value()") {
  errno = 0;
  //REQUIRE(std::strcmp(xsd_base64_value(""), "") == 0); // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:boolean */

TEST_CASE("xsd_boolean_validate()") {
  REQUIRE(xsd_boolean_validate("") == false);
  REQUIRE(xsd_boolean_validate("true") == true);
  REQUIRE(xsd_boolean_validate("false") == true);
  REQUIRE(xsd_boolean_validate("1") == true);
  REQUIRE(xsd_boolean_validate("0") == true);
  // TODO
}

TEST_CASE("xsd_boolean_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_boolean_value()") {
  errno = 0;
  REQUIRE(xsd_boolean_value("true") == true);
  REQUIRE(xsd_boolean_value("false") == false);
  REQUIRE(xsd_boolean_value("1") == true);
  REQUIRE(xsd_boolean_value("0") == false);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:date */

TEST_CASE("xsd_date_validate()") {
  REQUIRE(xsd_date_validate("") == false);
  REQUIRE(xsd_date_validate("1970-01-01") == true);
  // TODO
}

TEST_CASE("xsd_date_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_date_value()") {
  errno = 0;
  REQUIRE(xsd_date_value("1970-01-01") == 0);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:dateTime */

TEST_CASE("xsd_datetime_validate()") {
  REQUIRE(xsd_datetime_validate("") == false);
  REQUIRE(xsd_datetime_validate("1970-01-01T00:00:00") == true);
  // TODO
}

TEST_CASE("xsd_datetime_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_datetime_value()") {
  errno = 0;
  REQUIRE(xsd_datetime_value("1970-01-01T00:00:00") == 0);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:decimal */

TEST_CASE("xsd_decimal_validate()") {
  REQUIRE(xsd_decimal_validate("") == false);
  REQUIRE(xsd_decimal_validate("0") == true);
  REQUIRE(xsd_decimal_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_decimal_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_decimal_value()") {
  errno = 0;
  REQUIRE(xsd_decimal_value("0") == 0.0);
  //REQUIRE(xsd_decimal_value("0.5") == 0.5); // FIXME
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:double */

TEST_CASE("xsd_double_validate()") {
  REQUIRE(xsd_double_validate("") == false);
  REQUIRE(xsd_double_validate("0") == true);
  REQUIRE(xsd_double_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_double_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_double_value()") {
  errno = 0;
  REQUIRE(xsd_double_value("3.1415") == 3.1415);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:duration */

TEST_CASE("xsd_duration_validate()") {
  REQUIRE(xsd_duration_validate("") == false);
  // TODO
}

TEST_CASE("xsd_duration_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_duration_value()") {
  errno = 0;
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:float */

TEST_CASE("xsd_float_validate()") {
  REQUIRE(xsd_float_validate("") == false);
  REQUIRE(xsd_float_validate("0") == true);
  REQUIRE(xsd_float_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_float_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_float_value()") {
  errno = 0;
  REQUIRE(xsd_float_value("3.1415") == 3.1415f);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:integer */

TEST_CASE("xsd_integer_validate()") {
  REQUIRE(xsd_integer_validate("") == false);
  REQUIRE(xsd_integer_validate("0") == true);
  REQUIRE(xsd_integer_validate("0.0") == false);
  // TODO
}

TEST_CASE("xsd_integer_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_integer_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_int8_value()") {
  errno = 0;
  REQUIRE(xsd_int8_value("-129") == INT8_MIN);
  REQUIRE(xsd_int8_value("-128") == -128);
  REQUIRE(xsd_int8_value("0") == 0);
  REQUIRE(xsd_int8_value("127") == 127);
  REQUIRE(xsd_int8_value("128") == INT8_MAX);
}

TEST_CASE("xsd_int16_value()") {
  errno = 0;
  REQUIRE(xsd_int16_value("-32769") == INT16_MIN);
  REQUIRE(xsd_int16_value("-32768") == -32768);
  REQUIRE(xsd_int16_value("0") == 0);
  REQUIRE(xsd_int16_value("32767") == 32767);
  REQUIRE(xsd_int16_value("32768") == INT16_MAX);
}

TEST_CASE("xsd_int32_value()") {
  errno = 0;
  REQUIRE(xsd_int32_value("-2147483649") == INT32_MIN);
  REQUIRE(xsd_int32_value("-2147483648") == -2147483648);
  REQUIRE(xsd_int32_value("0") == 0);
  REQUIRE(xsd_int32_value("2147483647") == 2147483647);
  REQUIRE(xsd_int32_value("2147483648") == INT32_MAX);
}

TEST_CASE("xsd_int64_value()") {
  errno = 0;
  //REQUIRE(xsd_int64_value("-9223372036854775809") == INT64_MIN); // FIXME
  //REQUIRE(xsd_int64_value("-9223372036854775808") == -9223372036854775807LL-1); // FIXME
  REQUIRE(xsd_int64_value("0") == 0);
  REQUIRE(xsd_int64_value("9223372036854775807") == 9223372036854775807LL);
  REQUIRE(xsd_int64_value("9223372036854775808") == INT64_MAX);
}

TEST_CASE("xsd_intmax_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint8_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint16_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint32_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint64_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uintmax_value()") {
  errno = 0;
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:string */

TEST_CASE("xsd_string_validate()") {
  REQUIRE(xsd_string_validate("") == true);
  REQUIRE(xsd_string_validate("foobar") == true);
}

TEST_CASE("xsd_string_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_string_value()") {
  errno = 0;
  REQUIRE(std::strcmp(xsd_string_value(""), "") == 0);
  REQUIRE(std::strcmp(xsd_string_value(""), " ") != 0);
  REQUIRE(std::strcmp(xsd_string_value("foobar"), "foobar") == 0);
  REQUIRE(std::strcmp(xsd_string_value("foobar"), "FOOBAR") != 0);
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:time */

TEST_CASE("xsd_time_validate()") {
  REQUIRE(xsd_time_validate("") == false);
  REQUIRE(xsd_time_validate("00:00:00") == true);
  // TODO
}

TEST_CASE("xsd_time_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_time_value()") {
  errno = 0;
  SECTION("parsing invalid literals") {
    REQUIRE(xsd_time_value("T00:00:00") == 0);
    REQUIRE(errno == EINVAL);
  }
  SECTION("parsing literals without a timezone") {
    SECTION("the smallest value") {
      REQUIRE(xsd_time_value("00:00:00") == 0);
    }
    SECTION("the largest whole value") {
      REQUIRE(xsd_time_value("23:59:59") == 86399*1000000L);
    }
  }
  SECTION("parsing literals with a timezone") {
    SECTION("the smallest value with a Zulu timezone") {
      REQUIRE(xsd_time_value("00:00:00Z") == 0);
      REQUIRE(xsd_time_value("00:00:00+00:00") == 0);
    }
    SECTION("the smallest value with a non-Zulu timezone") {
      REQUIRE(xsd_time_value("06:00:00+06:00") == 0);
      REQUIRE(xsd_time_value("18:00:00-06:00") == 0);
    }
    SECTION("the largest whole value with a Zulu timezone") {
      REQUIRE(xsd_time_value("23:59:59Z") == 86399*1000000L);
    }
  }
}
<commit_msg>Added a missing header include in a test file.<commit_after>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "catch.hpp"

#include <xsd++/extern.h> /* for xsd_*_*() */

#include <cerrno>         /* for E*, errno */
#include <cmath>          /* for std::isinf(), std::isnan() */
#include <cstring>        /* for std::strcmp() */

////////////////////////////////////////////////////////////////////////////////
/* xsd:base64Binary */

TEST_CASE("xsd_base64_validate()") {
  //REQUIRE(xsd_base64_validate("") == false); // FIXME
  // TODO
}

TEST_CASE("xsd_base64_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_base64_value()") {
  errno = 0;
  //REQUIRE(std::strcmp(xsd_base64_value(""), "") == 0); // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:boolean */

TEST_CASE("xsd_boolean_validate()") {
  REQUIRE(xsd_boolean_validate("") == false);
  REQUIRE(xsd_boolean_validate("true") == true);
  REQUIRE(xsd_boolean_validate("false") == true);
  REQUIRE(xsd_boolean_validate("1") == true);
  REQUIRE(xsd_boolean_validate("0") == true);
  // TODO
}

TEST_CASE("xsd_boolean_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_boolean_value()") {
  errno = 0;
  REQUIRE(xsd_boolean_value("true") == true);
  REQUIRE(xsd_boolean_value("false") == false);
  REQUIRE(xsd_boolean_value("1") == true);
  REQUIRE(xsd_boolean_value("0") == false);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:date */

TEST_CASE("xsd_date_validate()") {
  REQUIRE(xsd_date_validate("") == false);
  REQUIRE(xsd_date_validate("1970-01-01") == true);
  // TODO
}

TEST_CASE("xsd_date_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_date_value()") {
  errno = 0;
  REQUIRE(xsd_date_value("1970-01-01") == 0);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:dateTime */

TEST_CASE("xsd_datetime_validate()") {
  REQUIRE(xsd_datetime_validate("") == false);
  REQUIRE(xsd_datetime_validate("1970-01-01T00:00:00") == true);
  // TODO
}

TEST_CASE("xsd_datetime_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_datetime_value()") {
  errno = 0;
  REQUIRE(xsd_datetime_value("1970-01-01T00:00:00") == 0);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:decimal */

TEST_CASE("xsd_decimal_validate()") {
  REQUIRE(xsd_decimal_validate("") == false);
  REQUIRE(xsd_decimal_validate("0") == true);
  REQUIRE(xsd_decimal_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_decimal_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_decimal_value()") {
  errno = 0;
  REQUIRE(xsd_decimal_value("0") == 0.0);
  //REQUIRE(xsd_decimal_value("0.5") == 0.5); // FIXME
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:double */

TEST_CASE("xsd_double_validate()") {
  REQUIRE(xsd_double_validate("") == false);
  REQUIRE(xsd_double_validate("0") == true);
  REQUIRE(xsd_double_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_double_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_double_value()") {
  errno = 0;
  REQUIRE(xsd_double_value("3.1415") == 3.1415);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:duration */

TEST_CASE("xsd_duration_validate()") {
  REQUIRE(xsd_duration_validate("") == false);
  // TODO
}

TEST_CASE("xsd_duration_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_duration_value()") {
  errno = 0;
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:float */

TEST_CASE("xsd_float_validate()") {
  REQUIRE(xsd_float_validate("") == false);
  REQUIRE(xsd_float_validate("0") == true);
  REQUIRE(xsd_float_validate("0.0") == true);
  // TODO
}

TEST_CASE("xsd_float_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_float_value()") {
  errno = 0;
  REQUIRE(xsd_float_value("3.1415") == 3.1415f);
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:integer */

TEST_CASE("xsd_integer_validate()") {
  REQUIRE(xsd_integer_validate("") == false);
  REQUIRE(xsd_integer_validate("0") == true);
  REQUIRE(xsd_integer_validate("0.0") == false);
  // TODO
}

TEST_CASE("xsd_integer_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_integer_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_int8_value()") {
  errno = 0;
  REQUIRE(xsd_int8_value("-129") == INT8_MIN);
  REQUIRE(xsd_int8_value("-128") == -128);
  REQUIRE(xsd_int8_value("0") == 0);
  REQUIRE(xsd_int8_value("127") == 127);
  REQUIRE(xsd_int8_value("128") == INT8_MAX);
}

TEST_CASE("xsd_int16_value()") {
  errno = 0;
  REQUIRE(xsd_int16_value("-32769") == INT16_MIN);
  REQUIRE(xsd_int16_value("-32768") == -32768);
  REQUIRE(xsd_int16_value("0") == 0);
  REQUIRE(xsd_int16_value("32767") == 32767);
  REQUIRE(xsd_int16_value("32768") == INT16_MAX);
}

TEST_CASE("xsd_int32_value()") {
  errno = 0;
  REQUIRE(xsd_int32_value("-2147483649") == INT32_MIN);
  REQUIRE(xsd_int32_value("-2147483648") == -2147483648);
  REQUIRE(xsd_int32_value("0") == 0);
  REQUIRE(xsd_int32_value("2147483647") == 2147483647);
  REQUIRE(xsd_int32_value("2147483648") == INT32_MAX);
}

TEST_CASE("xsd_int64_value()") {
  errno = 0;
  //REQUIRE(xsd_int64_value("-9223372036854775809") == INT64_MIN); // FIXME
  //REQUIRE(xsd_int64_value("-9223372036854775808") == -9223372036854775807LL-1); // FIXME
  REQUIRE(xsd_int64_value("0") == 0);
  REQUIRE(xsd_int64_value("9223372036854775807") == 9223372036854775807LL);
  REQUIRE(xsd_int64_value("9223372036854775808") == INT64_MAX);
}

TEST_CASE("xsd_intmax_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint8_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint16_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint32_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uint64_value()") {
  errno = 0;
  // TODO
}

TEST_CASE("xsd_uintmax_value()") {
  errno = 0;
  // TODO
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:string */

TEST_CASE("xsd_string_validate()") {
  REQUIRE(xsd_string_validate("") == true);
  REQUIRE(xsd_string_validate("foobar") == true);
}

TEST_CASE("xsd_string_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_string_value()") {
  errno = 0;
  REQUIRE(std::strcmp(xsd_string_value(""), "") == 0);
  REQUIRE(std::strcmp(xsd_string_value(""), " ") != 0);
  REQUIRE(std::strcmp(xsd_string_value("foobar"), "foobar") == 0);
  REQUIRE(std::strcmp(xsd_string_value("foobar"), "FOOBAR") != 0);
}

////////////////////////////////////////////////////////////////////////////////
/* xsd:time */

TEST_CASE("xsd_time_validate()") {
  REQUIRE(xsd_time_validate("") == false);
  REQUIRE(xsd_time_validate("00:00:00") == true);
  // TODO
}

TEST_CASE("xsd_time_canonicalize()") {
  // TODO
}

TEST_CASE("xsd_time_value()") {
  errno = 0;
  SECTION("parsing invalid literals") {
    REQUIRE(xsd_time_value("T00:00:00") == 0);
    REQUIRE(errno == EINVAL);
  }
  SECTION("parsing literals without a timezone") {
    SECTION("the smallest value") {
      REQUIRE(xsd_time_value("00:00:00") == 0);
    }
    SECTION("the largest whole value") {
      REQUIRE(xsd_time_value("23:59:59") == 86399*1000000L);
    }
  }
  SECTION("parsing literals with a timezone") {
    SECTION("the smallest value with a Zulu timezone") {
      REQUIRE(xsd_time_value("00:00:00Z") == 0);
      REQUIRE(xsd_time_value("00:00:00+00:00") == 0);
    }
    SECTION("the smallest value with a non-Zulu timezone") {
      REQUIRE(xsd_time_value("06:00:00+06:00") == 0);
      REQUIRE(xsd_time_value("18:00:00-06:00") == 0);
    }
    SECTION("the largest whole value with a Zulu timezone") {
      REQUIRE(xsd_time_value("23:59:59Z") == 86399*1000000L);
    }
  }
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_TEST_NO_LONGDOUBLE
#define EIGEN_TEST_NO_COMPLEX
#define EIGEN_TEST_FUNC cxx11_float16

#include "main.h"
#include <Eigen/src/Core/arch/CUDA/Half.h>

using Eigen::half;

void test_conversion()
{
  // Conversion from float.
  VERIFY_IS_EQUAL(half(1.0f).x, 0x3c00);
  VERIFY_IS_EQUAL(half(0.5f).x, 0x3800);
  VERIFY_IS_EQUAL(half(0.33333f).x, 0x3555);
  VERIFY_IS_EQUAL(half(0.0f).x, 0x0000);
  VERIFY_IS_EQUAL(half(-0.0f).x, 0x8000);
  VERIFY_IS_EQUAL(half(65504.0f).x, 0x7bff);
  VERIFY_IS_EQUAL(half(65536.0f).x, 0x7c00);  // Becomes infinity.

  // Denormals.
  VERIFY_IS_EQUAL(half(-5.96046e-08f).x, 0x8001);
  VERIFY_IS_EQUAL(half(5.96046e-08f).x, 0x0001);
  VERIFY_IS_EQUAL(half(1.19209e-07f).x, 0x0002);

  // Verify round-to-nearest-even behavior.
  float val1 = float(half(__half{0x3c00}));
  float val2 = float(half(__half{0x3c01}));
  float val3 = float(half(__half{0x3c02}));
  VERIFY_IS_EQUAL(half(0.5 * (val1 + val2)).x, 0x3c00);
  VERIFY_IS_EQUAL(half(0.5 * (val2 + val3)).x, 0x3c02);

  // Conversion from int.
  VERIFY_IS_EQUAL(half(-1).x, 0xbc00);
  VERIFY_IS_EQUAL(half(0).x, 0x0000);
  VERIFY_IS_EQUAL(half(1).x, 0x3c00);
  VERIFY_IS_EQUAL(half(2).x, 0x4000);
  VERIFY_IS_EQUAL(half(3).x, 0x4200);

  // Conversion from bool.
  VERIFY_IS_EQUAL(half(false).x, 0x0000);
  VERIFY_IS_EQUAL(half(true).x, 0x3c00);

  // Conversion to float.
  VERIFY_IS_EQUAL(float(half(__half{0x0000})), 0.0f);
  VERIFY_IS_EQUAL(float(half(__half{0x3c00})), 1.0f);

  // Denormals.
  VERIFY_IS_APPROX(float(half(__half{0x8001})), -5.96046e-08f);
  VERIFY_IS_APPROX(float(half(__half{0x0001})), 5.96046e-08f);
  VERIFY_IS_APPROX(float(half(__half{0x0002})), 1.19209e-07f);

  // NaNs and infinities.
  VERIFY(!(numext::isinf)(float(half(65504.0f))));  // Largest finite number.
  VERIFY(!(numext::isnan)(float(half(0.0f))));
  VERIFY((numext::isinf)(float(half(__half{0xfc00}))));
  VERIFY((numext::isnan)(float(half(__half{0xfc01}))));
  VERIFY((numext::isinf)(float(half(__half{0x7c00}))));
  VERIFY((numext::isnan)(float(half(__half{0x7c01}))));

#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY((numext::isnan)(float(half(0.0 / 0.0))));
  VERIFY((numext::isinf)(float(half(1.0 / 0.0))));
  VERIFY((numext::isinf)(float(half(-1.0 / 0.0))));
#endif

  // Exactly same checks as above, just directly on the half representation.
  VERIFY(!(numext::isinf)(half(__half{0x7bff})));
  VERIFY(!(numext::isnan)(half(__half{0x0000})));
  VERIFY((numext::isinf)(half(__half{0xfc00})));
  VERIFY((numext::isnan)(half(__half{0xfc01})));
  VERIFY((numext::isinf)(half(__half{0x7c00})));
  VERIFY((numext::isnan)(half(__half{0x7c01})));

#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY((numext::isnan)(half(0.0 / 0.0)));
  VERIFY((numext::isinf)(half(1.0 / 0.0)));
  VERIFY((numext::isinf)(half(-1.0 / 0.0)));
#endif
}

void test_arithmetic()
{
  VERIFY_IS_EQUAL(float(half(2) + half(2)), 4);
  VERIFY_IS_EQUAL(float(half(2) + half(-2)), 0);
  VERIFY_IS_APPROX(float(half(0.33333f) + half(0.66667f)), 1.0f);
  VERIFY_IS_EQUAL(float(half(2.0f) * half(-5.5f)), -11.0f);
  VERIFY_IS_APPROX(float(half(1.0f) / half(3.0f)), 0.33333f);
  VERIFY_IS_EQUAL(float(-half(4096.0f)), -4096.0f);
  VERIFY_IS_EQUAL(float(-half(-4096.0f)), 4096.0f);
}

void test_comparison()
{
  VERIFY(half(1.0f) > half(0.5f));
  VERIFY(half(0.5f) < half(1.0f));
  VERIFY(!(half(1.0f) < half(0.5f)));
  VERIFY(!(half(0.5f) > half(1.0f)));

  VERIFY(!(half(4.0f) > half(4.0f)));
  VERIFY(!(half(4.0f) < half(4.0f)));

  VERIFY(!(half(0.0f) < half(-0.0f)));
  VERIFY(!(half(-0.0f) < half(0.0f)));
  VERIFY(!(half(0.0f) > half(-0.0f)));
  VERIFY(!(half(-0.0f) > half(0.0f)));

  VERIFY(half(0.2f) > half(-1.0f));
  VERIFY(half(-1.0f) < half(0.2f));
  VERIFY(half(-16.0f) < half(-15.0f));

  VERIFY(half(1.0f) == half(1.0f));
  VERIFY(half(1.0f) != half(2.0f));

  // Comparisons with NaNs and infinities.
#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY(!(half(0.0 / 0.0) == half(0.0 / 0.0)));
  VERIFY(half(0.0 / 0.0) != half(0.0 / 0.0));

  VERIFY(!(half(1.0) == half(0.0 / 0.0)));
  VERIFY(!(half(1.0) < half(0.0 / 0.0)));
  VERIFY(!(half(1.0) > half(0.0 / 0.0)));
  VERIFY(half(1.0) != half(0.0 / 0.0));

  VERIFY(half(1.0) < half(1.0 / 0.0));
  VERIFY(half(1.0) > half(-1.0 / 0.0));
#endif
}

void test_functions()
{
  VERIFY_IS_EQUAL(float(numext::abs(half(3.5f))), 3.5f);
  VERIFY_IS_EQUAL(float(numext::abs(half(-3.5f))), 3.5f);

  VERIFY_IS_EQUAL(float(numext::exp(half(0.0f))), 1.0f);
  VERIFY_IS_APPROX(float(numext::exp(half(EIGEN_PI))), float(20.0 + EIGEN_PI));

  VERIFY_IS_EQUAL(float(numext::log(half(1.0f))), 0.0f);
  VERIFY_IS_APPROX(float(numext::log(half(10.0f))), 2.30273f);
}

void test_cxx11_float16()
{
  CALL_SUBTEST(test_conversion());
  CALL_SUBTEST(test_arithmetic());
  CALL_SUBTEST(test_comparison());
  CALL_SUBTEST(test_functions());
}
<commit_msg>Added basic test for trigonometric functions on fp16<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_TEST_NO_LONGDOUBLE
#define EIGEN_TEST_NO_COMPLEX
#define EIGEN_TEST_FUNC cxx11_float16

#include "main.h"
#include <Eigen/src/Core/arch/CUDA/Half.h>

using Eigen::half;

void test_conversion()
{
  // Conversion from float.
  VERIFY_IS_EQUAL(half(1.0f).x, 0x3c00);
  VERIFY_IS_EQUAL(half(0.5f).x, 0x3800);
  VERIFY_IS_EQUAL(half(0.33333f).x, 0x3555);
  VERIFY_IS_EQUAL(half(0.0f).x, 0x0000);
  VERIFY_IS_EQUAL(half(-0.0f).x, 0x8000);
  VERIFY_IS_EQUAL(half(65504.0f).x, 0x7bff);
  VERIFY_IS_EQUAL(half(65536.0f).x, 0x7c00);  // Becomes infinity.

  // Denormals.
  VERIFY_IS_EQUAL(half(-5.96046e-08f).x, 0x8001);
  VERIFY_IS_EQUAL(half(5.96046e-08f).x, 0x0001);
  VERIFY_IS_EQUAL(half(1.19209e-07f).x, 0x0002);

  // Verify round-to-nearest-even behavior.
  float val1 = float(half(__half{0x3c00}));
  float val2 = float(half(__half{0x3c01}));
  float val3 = float(half(__half{0x3c02}));
  VERIFY_IS_EQUAL(half(0.5 * (val1 + val2)).x, 0x3c00);
  VERIFY_IS_EQUAL(half(0.5 * (val2 + val3)).x, 0x3c02);

  // Conversion from int.
  VERIFY_IS_EQUAL(half(-1).x, 0xbc00);
  VERIFY_IS_EQUAL(half(0).x, 0x0000);
  VERIFY_IS_EQUAL(half(1).x, 0x3c00);
  VERIFY_IS_EQUAL(half(2).x, 0x4000);
  VERIFY_IS_EQUAL(half(3).x, 0x4200);

  // Conversion from bool.
  VERIFY_IS_EQUAL(half(false).x, 0x0000);
  VERIFY_IS_EQUAL(half(true).x, 0x3c00);

  // Conversion to float.
  VERIFY_IS_EQUAL(float(half(__half{0x0000})), 0.0f);
  VERIFY_IS_EQUAL(float(half(__half{0x3c00})), 1.0f);

  // Denormals.
  VERIFY_IS_APPROX(float(half(__half{0x8001})), -5.96046e-08f);
  VERIFY_IS_APPROX(float(half(__half{0x0001})), 5.96046e-08f);
  VERIFY_IS_APPROX(float(half(__half{0x0002})), 1.19209e-07f);

  // NaNs and infinities.
  VERIFY(!(numext::isinf)(float(half(65504.0f))));  // Largest finite number.
  VERIFY(!(numext::isnan)(float(half(0.0f))));
  VERIFY((numext::isinf)(float(half(__half{0xfc00}))));
  VERIFY((numext::isnan)(float(half(__half{0xfc01}))));
  VERIFY((numext::isinf)(float(half(__half{0x7c00}))));
  VERIFY((numext::isnan)(float(half(__half{0x7c01}))));

#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY((numext::isnan)(float(half(0.0 / 0.0))));
  VERIFY((numext::isinf)(float(half(1.0 / 0.0))));
  VERIFY((numext::isinf)(float(half(-1.0 / 0.0))));
#endif

  // Exactly same checks as above, just directly on the half representation.
  VERIFY(!(numext::isinf)(half(__half{0x7bff})));
  VERIFY(!(numext::isnan)(half(__half{0x0000})));
  VERIFY((numext::isinf)(half(__half{0xfc00})));
  VERIFY((numext::isnan)(half(__half{0xfc01})));
  VERIFY((numext::isinf)(half(__half{0x7c00})));
  VERIFY((numext::isnan)(half(__half{0x7c01})));

#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY((numext::isnan)(half(0.0 / 0.0)));
  VERIFY((numext::isinf)(half(1.0 / 0.0)));
  VERIFY((numext::isinf)(half(-1.0 / 0.0)));
#endif
}

void test_arithmetic()
{
  VERIFY_IS_EQUAL(float(half(2) + half(2)), 4);
  VERIFY_IS_EQUAL(float(half(2) + half(-2)), 0);
  VERIFY_IS_APPROX(float(half(0.33333f) + half(0.66667f)), 1.0f);
  VERIFY_IS_EQUAL(float(half(2.0f) * half(-5.5f)), -11.0f);
  VERIFY_IS_APPROX(float(half(1.0f) / half(3.0f)), 0.33333f);
  VERIFY_IS_EQUAL(float(-half(4096.0f)), -4096.0f);
  VERIFY_IS_EQUAL(float(-half(-4096.0f)), 4096.0f);
}

void test_comparison()
{
  VERIFY(half(1.0f) > half(0.5f));
  VERIFY(half(0.5f) < half(1.0f));
  VERIFY(!(half(1.0f) < half(0.5f)));
  VERIFY(!(half(0.5f) > half(1.0f)));

  VERIFY(!(half(4.0f) > half(4.0f)));
  VERIFY(!(half(4.0f) < half(4.0f)));

  VERIFY(!(half(0.0f) < half(-0.0f)));
  VERIFY(!(half(-0.0f) < half(0.0f)));
  VERIFY(!(half(0.0f) > half(-0.0f)));
  VERIFY(!(half(-0.0f) > half(0.0f)));

  VERIFY(half(0.2f) > half(-1.0f));
  VERIFY(half(-1.0f) < half(0.2f));
  VERIFY(half(-16.0f) < half(-15.0f));

  VERIFY(half(1.0f) == half(1.0f));
  VERIFY(half(1.0f) != half(2.0f));

  // Comparisons with NaNs and infinities.
#if !EIGEN_COMP_MSVC
  // Visual Studio errors out on divisions by 0
  VERIFY(!(half(0.0 / 0.0) == half(0.0 / 0.0)));
  VERIFY(half(0.0 / 0.0) != half(0.0 / 0.0));

  VERIFY(!(half(1.0) == half(0.0 / 0.0)));
  VERIFY(!(half(1.0) < half(0.0 / 0.0)));
  VERIFY(!(half(1.0) > half(0.0 / 0.0)));
  VERIFY(half(1.0) != half(0.0 / 0.0));

  VERIFY(half(1.0) < half(1.0 / 0.0));
  VERIFY(half(1.0) > half(-1.0 / 0.0));
#endif
}

void test_basic_functions()
{
  VERIFY_IS_EQUAL(float(numext::abs(half(3.5f))), 3.5f);
  VERIFY_IS_EQUAL(float(numext::abs(half(-3.5f))), 3.5f);

  VERIFY_IS_EQUAL(float(numext::exp(half(0.0f))), 1.0f);
  VERIFY_IS_APPROX(float(numext::exp(half(EIGEN_PI))), float(20.0 + EIGEN_PI));

  VERIFY_IS_EQUAL(float(numext::log(half(1.0f))), 0.0f);
  VERIFY_IS_APPROX(float(numext::log(half(10.0f))), 2.30273f);
}

void test_trigonometric_functions()
{
  VERIFY_IS_APPROX(numext::cos(half(0.0f)), half(cosf(0.0f)));
  VERIFY_IS_APPROX(numext::cos(half(EIGEN_PI)), half(cosf(EIGEN_PI)));
  //VERIFY_IS_APPROX(numext::cos(half(EIGEN_PI/2)), half(cosf(EIGEN_PI/2)));
  //VERIFY_IS_APPROX(numext::cos(half(3*EIGEN_PI/2)), half(cosf(3*EIGEN_PI/2)));
  VERIFY_IS_APPROX(numext::cos(half(3.5f)), half(cosf(3.5f)));

  VERIFY_IS_APPROX(numext::sin(half(0.0f)), half(sinf(0.0f)));
  //  VERIFY_IS_APPROX(numext::sin(half(EIGEN_PI)), half(sinf(EIGEN_PI)));
  VERIFY_IS_APPROX(numext::sin(half(EIGEN_PI/2)), half(sinf(EIGEN_PI/2)));
  VERIFY_IS_APPROX(numext::sin(half(3*EIGEN_PI/2)), half(sinf(3*EIGEN_PI/2)));
  VERIFY_IS_APPROX(numext::sin(half(3.5f)), half(sinf(3.5f)));

  VERIFY_IS_APPROX(numext::tan(half(0.0f)), half(tanf(0.0f)));
  //  VERIFY_IS_APPROX(numext::tan(half(EIGEN_PI)), half(tanf(EIGEN_PI)));
  //  VERIFY_IS_APPROX(numext::tan(half(EIGEN_PI/2)), half(tanf(EIGEN_PI/2)));
  //VERIFY_IS_APPROX(numext::tan(half(3*EIGEN_PI/2)), half(tanf(3*EIGEN_PI/2)));
  VERIFY_IS_APPROX(numext::tan(half(3.5f)), half(tanf(3.5f)));
}

void test_cxx11_float16()
{
  CALL_SUBTEST(test_conversion());
  CALL_SUBTEST(test_arithmetic());
  CALL_SUBTEST(test_comparison());
  CALL_SUBTEST(test_basic_functions());
  CALL_SUBTEST(test_trigonometric_functions());
}
<|endoftext|>


<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 "crypto/ec_signature_creator.h"

#include <cryptohi.h>
#include <pk11pub.h>
#include <secerr.h>
#include <sechash.h>

#include "base/logging.h"
#include "crypto/ec_private_key.h"
#include "crypto/nss_util.h"
#include "crypto/scoped_nss_types.h"

namespace crypto {

namespace {

SECStatus SignData(PLArenaPool* arena,
                   SECItem* result,
                   SECItem* input,
                   SECKEYPrivateKey* key,
                   HASH_HashType hash_type) {
  if (key->keyType != ecKey) {
    DLOG(FATAL) << "Should be using an EC key.";
    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    return SECFailure;
  }

  // Hash the input.
  std::vector<uint8> hash_data(HASH_ResultLen(hash_type));
  SECStatus rv = HASH_HashBuf(
      hash_type, &hash_data[0], input->data, input->len);
  if (rv != SECSuccess)
    return rv;
  SECItem hash = {siBuffer, &hash_data[0], hash_data.size()};

  // Compute signature of hash.
  int signature_len = PK11_SignatureLen(key);
  std::vector<uint8> signature_data(signature_len);
  SECItem sig = {siBuffer, &signature_data[0], signature_len};
  rv = PK11_Sign(key, &sig, &hash);
  if (rv != SECSuccess)
    return rv;

  // DER encode the signature.
  return DSAU_EncodeDerSigWithLen(result, &sig, sig.len);
}

}  // namespace

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  return new ECSignatureCreator(key);
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
    : key_(key) {
  EnsureNSSInit();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  // Data to be signed
  SECItem secret;
  secret.type = siBuffer;
  secret.len = data_len;
  secret.data = const_cast<unsigned char*>(data);

  // |arena| is used to encode the cert.
  crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
  CHECK(arena.get() != NULL);

  // Allocate space to contain the signed data.
  SECItem* result = SECITEM_AllocItem(arena.get(), NULL, 0);
  if (!result) {
    DLOG(ERROR) << "Unable to allocate space for signed data.";
    return false;
  }

  // Sign the secret data and save it to |result|.
  SECStatus rv =
      SignData(arena.get(), result, &secret, key_->key(), HASH_AlgSHA1);
  if (rv != SECSuccess) {
    DLOG(ERROR) << "DerSignData: " << PORT_GetError();
    return false;
  }

  // Copy the signed data into the output vector.
  signature->assign(result->data, result->data + result->len);
  return true;
}

}  // namespace crypto
<commit_msg>Fix an SECItem leak in the new ECSignatureCreator class.<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 "crypto/ec_signature_creator.h"

#include <cryptohi.h>
#include <pk11pub.h>
#include <secerr.h>
#include <sechash.h>

#include "base/logging.h"
#include "crypto/ec_private_key.h"
#include "crypto/nss_util.h"
#include "crypto/scoped_nss_types.h"

namespace crypto {

namespace {

SECStatus SignData(SECItem* result,
                   SECItem* input,
                   SECKEYPrivateKey* key,
                   HASH_HashType hash_type) {
  if (key->keyType != ecKey) {
    DLOG(FATAL) << "Should be using an EC key.";
    PORT_SetError(SEC_ERROR_INVALID_ARGS);
    return SECFailure;
  }

  // Hash the input.
  std::vector<uint8> hash_data(HASH_ResultLen(hash_type));
  SECStatus rv = HASH_HashBuf(
      hash_type, &hash_data[0], input->data, input->len);
  if (rv != SECSuccess)
    return rv;
  SECItem hash = {siBuffer, &hash_data[0], hash_data.size()};

  // Compute signature of hash.
  int signature_len = PK11_SignatureLen(key);
  std::vector<uint8> signature_data(signature_len);
  SECItem sig = {siBuffer, &signature_data[0], signature_len};
  rv = PK11_Sign(key, &sig, &hash);
  if (rv != SECSuccess)
    return rv;

  // DER encode the signature.
  return DSAU_EncodeDerSigWithLen(result, &sig, sig.len);
}

}  // namespace

// static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
  return new ECSignatureCreator(key);
}

ECSignatureCreator::ECSignatureCreator(ECPrivateKey* key)
    : key_(key) {
  EnsureNSSInit();
}

ECSignatureCreator::~ECSignatureCreator() { }

bool ECSignatureCreator::Sign(const uint8* data,
                              int data_len,
                              std::vector<uint8>* signature) {
  // Data to be signed
  SECItem secret;
  secret.type = siBuffer;
  secret.len = data_len;
  secret.data = const_cast<unsigned char*>(data);

  // SECItem to receive the output buffer.
  SECItem result;
  result.type = siBuffer;
  result.len = 0;
  result.data = NULL;

  // Sign the secret data and save it to |result|.
  SECStatus rv =
      SignData(&result, &secret, key_->key(), HASH_AlgSHA1);
  if (rv != SECSuccess) {
    DLOG(ERROR) << "DerSignData: " << PORT_GetError();
    return false;
  }

  // Copy the signed data into the output vector.
  signature->assign(result.data, result.data + result.len);
  SECITEM_FreeItem(&result, PR_FALSE /* only free |result.data| */);
  return true;
}

}  // namespace crypto
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "chrome/browser/chromeos/cros/mock_mount_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

namespace chromeos {

using testing::_;
using testing::Invoke;

const char* kTestSystemPath = "/this/system/path";
const char* kTestDevicePath = "/this/device/path";
const char* kTestMountPath = "/media/foofoo";

void MockMountLibrary::AddObserverInternal(MountLibrary::Observer* observer) {
  observers_.AddObserver(observer);
}

void MockMountLibrary::RemoveObserverInternal(MountLibrary::Observer* observer) {
  observers_.RemoveObserver(observer);
}

MockMountLibrary::MockMountLibrary() {
  ON_CALL(*this, AddObserver(_))
      .WillByDefault(Invoke(this, &MockMountLibrary::AddObserverInternal));
  ON_CALL(*this, RemoveObserver(_))
      .WillByDefault(Invoke(this, &MockMountLibrary::RemoveObserverInternal));
  ON_CALL(*this, disks())
      .WillByDefault(Invoke(this, &MockMountLibrary::disksInternal));
}

MockMountLibrary::~MockMountLibrary() {

}

void MockMountLibrary::FireDeviceInsertEvents() {

  disks_.clear();

  disks_.push_back(Disk(kTestDevicePath, "",  kTestSystemPath));

  // Device Added
  chromeos::MountEventType evt;
  evt = chromeos::DEVICE_ADDED;
  UpdateMountStatus(evt, kTestSystemPath);

  // Disk Added
  evt = chromeos::DISK_ADDED;
  UpdateMountStatus(evt, kTestDevicePath);

  // Disk Changed
  disks_.clear();
  disks_.push_back(Disk(kTestDevicePath, kTestMountPath, kTestSystemPath));
  evt = chromeos::DISK_CHANGED;
  UpdateMountStatus(evt, kTestDevicePath);
}

void MockMountLibrary::FireDeviceRemoveEvents() {
  disks_.clear();
  chromeos::MountEventType evt;
  evt = chromeos::DISK_REMOVED;
  UpdateMountStatus(evt, kTestDevicePath);
}

void MockMountLibrary::UpdateMountStatus(MountEventType evt,
                                         const std::string& path) {
  // Make sure we run on UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  FOR_EACH_OBSERVER(Observer, observers_, MountChanged(this, evt, path));
}

}  // namespace chromeos
<commit_msg>updating test Review URL: http://codereview.chromium.org/1551015<commit_after>// Copyright (c) 2009 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 "chrome/browser/chromeos/cros/mock_mount_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

namespace chromeos {

using testing::_;
using testing::Invoke;

const char* kTestSystemPath = "/this/system/path";
const char* kTestDevicePath = "/this/device/path";
const char* kTestMountPath = "/media/foofoo";

void MockMountLibrary::AddObserverInternal(MountLibrary::Observer* observer) {
  observers_.AddObserver(observer);
}

void MockMountLibrary::RemoveObserverInternal(MountLibrary::Observer* observer) {
  observers_.RemoveObserver(observer);
}

MockMountLibrary::MockMountLibrary() {
  ON_CALL(*this, AddObserver(_))
      .WillByDefault(Invoke(this, &MockMountLibrary::AddObserverInternal));
  ON_CALL(*this, RemoveObserver(_))
      .WillByDefault(Invoke(this, &MockMountLibrary::RemoveObserverInternal));
  ON_CALL(*this, disks())
      .WillByDefault(Invoke(this, &MockMountLibrary::disksInternal));
}

MockMountLibrary::~MockMountLibrary() {

}

void MockMountLibrary::FireDeviceInsertEvents() {

  disks_.clear();

  disks_.push_back(Disk(kTestDevicePath, "",  kTestSystemPath, false, true));

  // Device Added
  chromeos::MountEventType evt;
  evt = chromeos::DEVICE_ADDED;
  UpdateMountStatus(evt, kTestSystemPath);

  // Disk Added
  evt = chromeos::DISK_ADDED;
  UpdateMountStatus(evt, kTestDevicePath);

  // Disk Changed
  disks_.clear();
  disks_.push_back(Disk(kTestDevicePath, kTestMountPath, kTestSystemPath, false, true));
  evt = chromeos::DISK_CHANGED;
  UpdateMountStatus(evt, kTestDevicePath);
}

void MockMountLibrary::FireDeviceRemoveEvents() {
  disks_.clear();
  chromeos::MountEventType evt;
  evt = chromeos::DISK_REMOVED;
  UpdateMountStatus(evt, kTestDevicePath);
}

void MockMountLibrary::UpdateMountStatus(MountEventType evt,
                                         const std::string& path) {
  // Make sure we run on UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  FOR_EACH_OBSERVER(Observer, observers_, MountChanged(this, evt, path));
}

}  // namespace chromeos
<|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 "chrome/browser/chromeos/login/user_image_loader.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/login/image_decoder.h"
#include "content/browser/browser_thread.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"

namespace chromeos {

UserImageLoader::UserImageLoader(Delegate* delegate)
    : target_message_loop_(NULL),
      delegate_(delegate) {
}

UserImageLoader::~UserImageLoader() {
}

void UserImageLoader::Start(const std::string& username,
                            const std::string& filename,
                            bool should_save_image) {
  target_message_loop_ = MessageLoop::current();

  ImageInfo image_info(username, should_save_image);
  BrowserThread::PostTask(BrowserThread::FILE,
                          FROM_HERE,
                          NewRunnableMethod(this,
                                            &UserImageLoader::LoadImage,
                                            filename,
                                            image_info));
}

void UserImageLoader::LoadImage(const std::string& filepath,
                                const ImageInfo& image_info) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  std::string image_data;
  file_util::ReadFileToString(FilePath(filepath), &image_data);

  scoped_refptr<ImageDecoder> image_decoder =
      new ImageDecoder(this, image_data);
  image_info_map_.insert(std::make_pair(image_decoder.get(), image_info));
  image_decoder->Start();
}

void UserImageLoader::OnImageDecoded(const ImageDecoder* decoder,
                                     const SkBitmap& decoded_image) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  ImageInfoMap::iterator info_it = image_info_map_.find(decoder);
  if (info_it == image_info_map_.end()) {
    NOTREACHED();
    return;
  }
  target_message_loop_->PostTask(FROM_HERE,
      NewRunnableMethod(this,
                        &UserImageLoader::NotifyDelegate,
                        decoded_image,
                        info_it->second));
  image_info_map_.erase(info_it);
}

void UserImageLoader::OnDecodeImageFailed(const ImageDecoder* decoder) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  image_info_map_.erase(decoder);
}

void UserImageLoader::NotifyDelegate(const SkBitmap& image,
                                     const ImageInfo& image_info) {
  if (delegate_) {
    delegate_->OnImageLoaded(image_info.username,
                             image,
                             image_info.should_save_image);
  }
}

}  // namespace chromeos
<commit_msg>Remove map entry when it's not needed. Avoid one copy. Removed unnecessary include. Added cropping of the image if it should be saved.<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 "chrome/browser/chromeos/login/user_image_loader.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/login/image_decoder.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "content/browser/browser_thread.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/skbitmap_operations.h"

namespace chromeos {

UserImageLoader::UserImageLoader(Delegate* delegate)
    : target_message_loop_(NULL),
      delegate_(delegate) {
}

UserImageLoader::~UserImageLoader() {
}

void UserImageLoader::Start(const std::string& username,
                            const std::string& filename,
                            bool should_save_image) {
  target_message_loop_ = MessageLoop::current();

  ImageInfo image_info(username, should_save_image);
  BrowserThread::PostTask(BrowserThread::FILE,
                          FROM_HERE,
                          NewRunnableMethod(this,
                                            &UserImageLoader::LoadImage,
                                            filename,
                                            image_info));
}

void UserImageLoader::LoadImage(const std::string& filepath,
                                const ImageInfo& image_info) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  std::string image_data;
  file_util::ReadFileToString(FilePath(filepath), &image_data);

  scoped_refptr<ImageDecoder> image_decoder =
      new ImageDecoder(this, image_data);
  image_info_map_.insert(std::make_pair(image_decoder.get(), image_info));
  image_decoder->Start();
}

void UserImageLoader::OnImageDecoded(const ImageDecoder* decoder,
                                     const SkBitmap& decoded_image) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  ImageInfoMap::iterator info_it = image_info_map_.find(decoder);
  if (info_it == image_info_map_.end()) {
    NOTREACHED();
    return;
  }
  ImageInfo image_info = info_it->second;
  SkBitmap final_image = decoded_image;
  if (image_info.should_save_image) {
    // Auto crop the image, taking the largest square in the center.
    // Also make the image smaller to save space and memory.
    int size = std::min(decoded_image.width(), decoded_image.height());
    int x = (decoded_image.width() - size) / 2;
    int y = (decoded_image.height() - size) / 2;
    SkBitmap cropped_image =
        SkBitmapOperations::CreateTiledBitmap(decoded_image, x, y, size, size);
    final_image =
        skia::ImageOperations::Resize(cropped_image,
                                      skia::ImageOperations::RESIZE_LANCZOS3,
                                      login::kUserImageSize,
                                      login::kUserImageSize);
  }
  target_message_loop_->PostTask(FROM_HERE,
      NewRunnableMethod(this,
                        &UserImageLoader::NotifyDelegate,
                        final_image,
                        image_info));
  image_info_map_.erase(info_it);
}

void UserImageLoader::OnDecodeImageFailed(const ImageDecoder* decoder) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  image_info_map_.erase(decoder);
}

void UserImageLoader::NotifyDelegate(const SkBitmap& image,
                                     const ImageInfo& image_info) {
  if (delegate_) {
    delegate_->OnImageLoaded(image_info.username,
                             image,
                             image_info.should_save_image);
  }
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// INCLUDE FILES
#include "bluetoothlinkmanagerdevicediscoverer.h"
#include "qbluetoothaddress.h"
#include "qbluetoothdeviceinfo.h"
#include <qstring.h>

#include "utils_symbian_p.h"
#include <qdebug.h>

QTM_BEGIN_NAMESPACE

/*!
    \class BluetoothLinkManagerDeviceDiscoverer
    \brief The BluetoothLinkManagerDeviceDiscoverer is class searches other bluetooth devices.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity

    BluetoothLinkManagerDeviceDiscoverer is an Symbian ActiveObject derived class that discovers
    other Bluetooth devices using "BTLinkManager" protocol.

    When Bluetoothdevices are found signal deviceDiscovered(QBluetoothDeviceInfo &) is emitted. When
    all devices are found (or none) signal deviceDiscoveryComplete() is emitted.

    In case of an error signal linkManagerError(int error) is emitted. In the case of errorSignal
    one should consider deleting this class and creating it again.
*/

_LIT(KBTLinkManagerTxt,"BTLinkManager");

BluetoothLinkManagerDeviceDiscoverer::BluetoothLinkManagerDeviceDiscoverer(RSocketServ &socketServer,QObject *parent)
    : QObject(parent)
    , CActive(CActive::EPriorityStandard)
    , m_socketServer(socketServer)
{
    TInt result;

    /* find Bluetooth protocol */
    TProtocolDesc protocol;
    result = m_socketServer.FindProtocol(KBTLinkManagerTxt(),protocol);
    if (result != KErrNone) {
        setError(result);
    }
    /* Create and initialise an RHostResolver */
    result = m_hostResolver.Open(m_socketServer, protocol.iAddrFamily, protocol.iProtocol);
    if (result != KErrNone) {
        setError(result);
    }

    //add this active object to scheduler
    CActiveScheduler::Add(this);
}

BluetoothLinkManagerDeviceDiscoverer::~BluetoothLinkManagerDeviceDiscoverer()
{
    // cancel active object
    Cancel();
    m_hostResolver.Close();
}
/*!
    Starts up device discovery. When devices are discovered signal deviceDiscovered is emitted.
    After signal deviceDiscoveryComplete() is emitted new discovery request can be made
    Leaves with KErrNotReady if discovery is ongoing and new discovery is started

*/
void BluetoothLinkManagerDeviceDiscoverer::StartDiscoveryL(const uint discoveryType)
{
    if (!IsActive()) {
        m_addr.SetIAC( discoveryType );
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache);
        m_hostResolver.GetByAddress(m_addr, m_entry, iStatus);
        SetActive();
    }
    else {
        User::Leave(KErrNotReady);
    }
}
/*!
  Informs that our request has been prosessed and the data is available to be used.
*/
void BluetoothLinkManagerDeviceDiscoverer::RunL()
{
    if (iStatus.Int() != KErrNone)
        emit deviceDiscoveryComplete(iStatus.Int());
    else {
        emit deviceDiscovered(currentDeviceDataToQBluetoothDeviceInfo());
        // get next (possible) discovered device
        m_hostResolver.Next(m_entry, iStatus);
        // set this AO active ie running
        SetActive();
    }
}
/*!
  Cancel current request.
*/
void BluetoothLinkManagerDeviceDiscoverer::DoCancel()
{
    m_hostResolver.Cancel();
}
/*!
  Stops the discovery. Signal deviceDiscoveryComplete(int) with KErrCancel might be emitted.
*/
void BluetoothLinkManagerDeviceDiscoverer::Stop()
{
    Cancel();
}

/*!
    Transforms Symbian device name, address and service classes to QBluetootDeviceInfo.
*/
QBluetoothDeviceInfo BluetoothLinkManagerDeviceDiscoverer::currentDeviceDataToQBluetoothDeviceInfo() const
{
    // extract device information from results and map them to QBluetoothDeviceInfo
    // device name
    THostName symbianDeviceName = m_entry().iName;
    QString deviceName = QString::fromUtf16(symbianDeviceName.Ptr(), symbianDeviceName.Length()).toUpper();

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);
    qDebug()<< "Discovered device: name="<< deviceName <<", address=" << bluetoothAddress.toString() <<", class=" << deviceClass;
    return deviceInfo;
}
void BluetoothLinkManagerDeviceDiscoverer::setError(int errorCode)
{
    QString errorDescription;
    switch (errorCode) {
        case KLinkManagerErrBase:
            errorDescription.append("Link manager base error value or Insufficient baseband resources error value");
            break;
        case KErrProxyWriteNotAvailable:
            errorDescription.append("Proxy write not available error value");
            break;
        case KErrReflexiveBluetoothLink:
            errorDescription.append("Reflexive BT link error value");
            break;
        case KErrPendingPhysicalLink:
            errorDescription.append("Physical link connection already pending when trying to connect the physical link");
            break;
        case KErrRemoteDeviceIndicatedNoBonding:
            errorDescription.append("Dedicated bonding attempt failure when the remote device responds with No-Bonding");
            break;
        case KErrNotReady:
            errorDescription.append("KErrNotReady");
        default:
            break;
    }
    if (errorCode == KErrCancel)
        emit linkManagerError(QBluetoothDeviceDiscoveryAgent::Canceled);
    else if (errorCode != KErrNone)
        emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError);
}
#include "moc_bluetoothlinkmanagerdevicediscoverer.cpp"

QTM_END_NAMESPACE
<commit_msg>Symbian: Close HostResolver session after device discovery complete<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

// INCLUDE FILES
#include "bluetoothlinkmanagerdevicediscoverer.h"
#include "qbluetoothaddress.h"
#include "qbluetoothdeviceinfo.h"
#include <qstring.h>

#include "utils_symbian_p.h"
#include <qdebug.h>

QTM_BEGIN_NAMESPACE

/*!
    \class BluetoothLinkManagerDeviceDiscoverer
    \brief The BluetoothLinkManagerDeviceDiscoverer is class searches other bluetooth devices.

    \ingroup connectivity-bluetooth
    \inmodule QtConnectivity

    BluetoothLinkManagerDeviceDiscoverer is an Symbian ActiveObject derived class that discovers
    other Bluetooth devices using "BTLinkManager" protocol.

    When Bluetoothdevices are found signal deviceDiscovered(QBluetoothDeviceInfo &) is emitted. When
    all devices are found (or none) signal deviceDiscoveryComplete() is emitted.

    In case of an error signal linkManagerError(int error) is emitted. In the case of errorSignal
    one should consider deleting this class and creating it again.
*/

_LIT(KBTLinkManagerTxt,"BTLinkManager");

BluetoothLinkManagerDeviceDiscoverer::BluetoothLinkManagerDeviceDiscoverer(RSocketServ &socketServer,QObject *parent)
    : QObject(parent)
    , CActive(CActive::EPriorityStandard)
    , m_socketServer(socketServer)
{
    TInt result;

    /* find Bluetooth protocol */
    TProtocolDesc protocol;
    result = m_socketServer.FindProtocol(KBTLinkManagerTxt(),protocol);
    if (result != KErrNone) {
        setError(result);
    }
    /* Create and initialise an RHostResolver */
    result = m_hostResolver.Open(m_socketServer, protocol.iAddrFamily, protocol.iProtocol);
    if (result != KErrNone) {
        setError(result);
    }

    //add this active object to scheduler
    CActiveScheduler::Add(this);
}

BluetoothLinkManagerDeviceDiscoverer::~BluetoothLinkManagerDeviceDiscoverer()
{
    // cancel active object
    Cancel();
    m_hostResolver.Close();
}
/*!
    Starts up device discovery. When devices are discovered signal deviceDiscovered is emitted.
    After signal deviceDiscoveryComplete() is emitted new discovery request can be made
    Leaves with KErrNotReady if discovery is ongoing and new discovery is started

*/
void BluetoothLinkManagerDeviceDiscoverer::StartDiscoveryL(const uint discoveryType)
{
    if (!IsActive()) {
        m_addr.SetIAC( discoveryType );
        m_addr.SetAction(KHostResInquiry | KHostResName | KHostResIgnoreCache);
        m_hostResolver.GetByAddress(m_addr, m_entry, iStatus);
        SetActive();
    }
    else {
        User::Leave(KErrNotReady);
    }
}
/*!
  Informs that our request has been prosessed and the data is available to be used.
*/
void BluetoothLinkManagerDeviceDiscoverer::RunL()
{
    if (iStatus.Int() != KErrNone) {
        emit deviceDiscoveryComplete(iStatus.Int());
        // it is advised to close host resolver session after it has been used.
        m_hostResolver.Close();
    }
    else {
        emit deviceDiscovered(currentDeviceDataToQBluetoothDeviceInfo());
        // get next (possible) discovered device
        m_hostResolver.Next(m_entry, iStatus);
        // set this AO active ie running
        SetActive();
    }
}
/*!
  Cancel current request.
*/
void BluetoothLinkManagerDeviceDiscoverer::DoCancel()
{
    m_hostResolver.Cancel();
}
/*!
  Stops the discovery. Signal deviceDiscoveryComplete(int) with KErrCancel might be emitted.
*/
void BluetoothLinkManagerDeviceDiscoverer::Stop()
{
    Cancel();
}

/*!
    Transforms Symbian device name, address and service classes to QBluetootDeviceInfo.
*/
QBluetoothDeviceInfo BluetoothLinkManagerDeviceDiscoverer::currentDeviceDataToQBluetoothDeviceInfo() const
{
    // extract device information from results and map them to QBluetoothDeviceInfo
    // device name
    THostName symbianDeviceName = m_entry().iName;
    QString deviceName = QString::fromUtf16(symbianDeviceName.Ptr(), symbianDeviceName.Length()).toUpper();

    // unique address of the device
    const TBTDevAddr symbianDeviceAddress = static_cast<TBTSockAddr> (m_entry().iAddr).BTAddr();
    QBluetoothAddress bluetoothAddress = qTBTDevAddrToQBluetoothAddress(symbianDeviceAddress);

    // format symbian major/minor numbers
    quint32 deviceClass = qTPackSymbianDeviceClass(m_addr);

    QBluetoothDeviceInfo deviceInfo(bluetoothAddress, deviceName, deviceClass);
    qDebug()<< "Discovered device: name="<< deviceName <<", address=" << bluetoothAddress.toString() <<", class=" << deviceClass;
    return deviceInfo;
}
void BluetoothLinkManagerDeviceDiscoverer::setError(int errorCode)
{
    QString errorDescription;
    switch (errorCode) {
        case KLinkManagerErrBase:
            errorDescription.append("Link manager base error value or Insufficient baseband resources error value");
            break;
        case KErrProxyWriteNotAvailable:
            errorDescription.append("Proxy write not available error value");
            break;
        case KErrReflexiveBluetoothLink:
            errorDescription.append("Reflexive BT link error value");
            break;
        case KErrPendingPhysicalLink:
            errorDescription.append("Physical link connection already pending when trying to connect the physical link");
            break;
        case KErrRemoteDeviceIndicatedNoBonding:
            errorDescription.append("Dedicated bonding attempt failure when the remote device responds with No-Bonding");
            break;
        case KErrNotReady:
            errorDescription.append("KErrNotReady");
        default:
            break;
    }
    if (errorCode == KErrCancel)
        emit linkManagerError(QBluetoothDeviceDiscoveryAgent::Canceled);
    else if (errorCode != KErrNone)
        emit linkManagerError(QBluetoothDeviceDiscoveryAgent::UnknownError);
}
#include "moc_bluetoothlinkmanagerdevicediscoverer.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#include <string>

#include "command/standard/selectCommand.h"
#include "core/selection.h"
#include "core/uidHelpers.h"
#include "core.h"

using namespace pixeleditor;

Command* SelectCommand::Create()
{
    return new SelectCommand();
}

std::string SelectCommand::GetStaticName()
{
    return "select";
}

std::string SelectCommand::GetName()
{
    return SelectCommand::GetStaticName();
}

SelectCommand::SelectCommand()
{

}

SelectCommand::~SelectCommand()
{

}

bool SelectCommand::CanUndo()
{
    return true;
}

bool SelectCommand::Do(std::string& returnString)
{
    _Selection = Core::Instance()->GetSelection();

    Selection newSelection;

    if (IsArgumentSet("c"))
    {
        Core::Instance()->SetSelection(newSelection);
        return true;
    }

    if (IsArgumentSet("a"))
        newSelection = _Selection;

    if (IsArgumentSet("u"))
    {
        unsigned long count = GetArgumentCount("u");

        for (int i=0; i<count; i++)
        {
            std::string id = GetArgument("u", i);

            newSelection.AddEntity(GenerateSelectionUid(atoi(id.c_str())));
        }

        Core::Instance()->SetSelection(newSelection);

        return true;
    }

    return false;
}

bool SelectCommand::Undo()
{
    Core::Instance()->SetSelection(_Selection);

    return true;
}
<commit_msg>Fix compilation issue<commit_after>#include <cstdlib>
#include <string>

#include "command/standard/selectCommand.h"
#include "core/selection.h"
#include "core/uidHelpers.h"
#include "core.h"

using namespace pixeleditor;

Command* SelectCommand::Create()
{
    return new SelectCommand();
}

std::string SelectCommand::GetStaticName()
{
    return "select";
}

std::string SelectCommand::GetName()
{
    return SelectCommand::GetStaticName();
}

SelectCommand::SelectCommand()
{

}

SelectCommand::~SelectCommand()
{

}

bool SelectCommand::CanUndo()
{
    return true;
}

bool SelectCommand::Do(std::string& returnString)
{
    _Selection = Core::Instance()->GetSelection();

    Selection newSelection;

    if (IsArgumentSet("c"))
    {
        Core::Instance()->SetSelection(newSelection);
        return true;
    }

    if (IsArgumentSet("a"))
        newSelection = _Selection;

    if (IsArgumentSet("u"))
    {
        unsigned long count = GetArgumentCount("u");

        for (int i=0; i<count; i++)
        {
            std::string id = GetArgument("u", i);

            newSelection.AddEntity(GenerateSelectionUid(atoi(id.c_str())));
        }

        Core::Instance()->SetSelection(newSelection);

        return true;
    }

    return false;
}

bool SelectCommand::Undo()
{
    Core::Instance()->SetSelection(_Selection);

    return true;
}
<|endoftext|>