Merge branch 'google3'

Change-Id: Ibebf84b98939ee8e5006beedc34d225e8c2dd413
This commit is contained in:
Alexey Polyudov
2020-05-28 01:36:50 -07:00
337 changed files with 20487 additions and 1586 deletions
+16 -67
View File
@@ -2,16 +2,16 @@ cc_library(
name = "utils",
srcs = [
"base64_utils.cc",
"cancelable_alarm.cc",
"file_impl.cc",
"pipe.cc",
"prng.cc",
"reliability_utils.cc",
],
hdrs = [
"base64_utils.h",
"cancelable_alarm.cc",
"cancelable_alarm.h",
"file_impl.h",
"pipe.cc",
"pipe.h",
"prng.h",
"reliability_utils.h",
@@ -50,7 +50,6 @@ cc_library(
],
deps = [
":logging",
"//platform/impl/default:lock",
"//platform/port:down_cast",
"//platform/port:string",
],
@@ -64,6 +63,7 @@ cc_library(
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core:__subpackages__",
"//platform_v2/public:__pkg__",
],
deps = [
"//absl/base",
@@ -72,75 +72,24 @@ cc_library(
)
cc_test(
name = "container_of_test",
srcs = ["container_of_test.cc"],
deps = [
":types",
"//testing/base/public:gunit_main",
name = "platform_test",
timeout = "short",
srcs = [
"atomic_reference_test.cc",
"byte_array_test.cc",
"container_of_test.cc",
"file_impl_test.cc",
"pipe_test.cc",
"prng_test.cc",
"ptr_test.cc",
"settable_future_test.cc",
],
)
cc_test(
name = "ptr_test",
srcs = ["ptr_test.cc"],
deps = [
":types",
"//testing/base/public:gunit_main",
],
)
cc_test(
name = "prng_test",
srcs = ["prng_test.cc"],
deps = [
":utils",
"//testing/base/public:gunit_main",
],
)
cc_test(
name = "file_test",
srcs = ["file_impl_test.cc"],
deps = [
":utils",
"//file/util:temp_path",
"//testing/base/public:gunit_main",
],
)
cc_test(
name = "exception_test",
srcs = ["exception_test.cc"],
deps = [
":types",
"//testing/base/public:gunit_main",
],
)
cc_test(
name = "pipe_test",
timeout = "short",
srcs = ["pipe_test.cc"],
deps = [
":utils",
"//platform:types",
"//platform/impl/default:condition_variable",
"//platform/impl/default:lock",
"//platform/port:string",
"//testing/base/public:gunit_main",
"//absl/time",
],
)
cc_test(
name = "byte_array_test",
timeout = "short",
srcs = ["byte_array_test.cc"],
deps = [
":utils",
"//platform:types",
"//platform/impl/default:condition_variable",
"//platform/impl/default:lock",
"//platform/api",
"//platform/impl/g3",
"//platform/port:string",
"//testing/base/public:gunit_main",
"//absl/time",
+14 -10
View File
@@ -1,11 +1,14 @@
add_library(platform_utils STATIC
base64_utils.cc
file_impl.cc
prng.cc
reliability_utils.cc
)
target_sources(platform_utils
PRIVATE
base64_utils.cc
cancelable_alarm.cc
file_impl.cc
pipe.cc
prng.cc
reliability_utils.cc
PUBLIC
base64_utils.h
cancelable_alarm.h
@@ -18,8 +21,11 @@ target_sources(platform_utils
target_link_libraries(platform_utils
PUBLIC
platform_types
platform_api
platform_types
platform_impl_g3
platform_impl_shared_posix_lock
platform_impl_shared_posix_condition_variable
absl::strings
)
@@ -62,8 +68,7 @@ target_link_libraries(platform_test
gtest
gtest_main
platform_api
platform_impl_default_cond_var
platform_impl_default_lock
platform_impl_g3
platform_types
platform_utils
)
@@ -74,7 +79,6 @@ add_test(
)
add_subdirectory(api)
add_subdirectory(api2)
add_subdirectory(impl/sample)
add_subdirectory(impl/default)
add_subdirectory(impl/g3)
add_subdirectory(impl/shared)
add_subdirectory(port)
+7 -1
View File
@@ -9,6 +9,7 @@ cc_library(
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"atomic_reference_def.h",
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
@@ -25,12 +26,15 @@ cc_library(
"multi_thread_executor.h",
"output_file.h",
"output_stream.h",
"platform.h",
"scheduled_executor.h",
"server_sync.h",
"settable_future.h",
"settable_future_def.h",
"single_thread_executor.h",
"socket.h",
"submittable_executor.h",
"submittable_executor_def.h",
"system_clock.h",
"thread_utils.h",
"webrtc.h",
@@ -41,7 +45,9 @@ cc_library(
"//platform:types",
"//platform/port:down_cast",
"//platform/port:string",
"//webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
"//absl/strings",
"//absl/types:any",
"//webrtc/api:libjingle_peerconnection_api",
],
)
+34 -7
View File
@@ -1,21 +1,48 @@
#ifndef PLATFORM_API_ATOMIC_REFERENCE_H_
#define PLATFORM_API_ATOMIC_REFERENCE_H_
#include "platform/api/atomic_reference_def.h"
#include "platform/api/platform.h"
#include "platform/ptr.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
// An object reference that may be updated atomically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
namespace platform {
namespace impl {
template <typename T>
class AtomicReference {
class AtomicReferenceImpl : public AtomicReference<T> {
public:
virtual ~AtomicReference() {}
explicit AtomicReferenceImpl(T initial_value) {
atomic_ = platform::ImplementationPlatform::createAtomicReferenceAny(
absl::any(initial_value));
}
virtual T get() = 0;
virtual void set(T value) = 0;
~AtomicReferenceImpl() override = default;
void set(T new_value) override { atomic_->set(absl::any(new_value)); }
T get() override { return absl::any_cast<T>(atomic_->get()); }
private:
Ptr<AtomicReference<absl::any>> atomic_;
};
} // namespace impl
template <typename T>
Ptr<AtomicReference<T>> ImplementationPlatform::createAtomicReference(
T initial_value) {
return Ptr<AtomicReference<T>>(
new impl::AtomicReferenceImpl<T>{initial_value});
}
} // namespace platform
} // namespace nearby
} // namespace location
+27
View File
@@ -0,0 +1,27 @@
#ifndef PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
#define PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
namespace location {
namespace nearby {
// An object reference that may be updated atomically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
//
// Platform must implentent non-template static member functions
// Ptr<AtomicReference<size_t>> CreateAtomicReferenceSizeT()
// Ptr<AtomicReference<std::shared_ptr<void>>> CreateAtomicReferencePtr()
// in the location::nearby::platform::ImplementationPlatform class.
template <typename T>
class AtomicReference {
public:
virtual ~AtomicReference() = default;
virtual T get() = 0;
virtual void set(T value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_ATOMIC_REFERENCE_DEF_H_
+1 -1
View File
@@ -24,7 +24,7 @@ namespace nearby {
struct BLEAdvertisementData {
typedef std::int8_t TXPowerLevel;
static const TXPowerLevel UNSPECIFIED_TX_POWER_LEVEL =
static constexpr TXPowerLevel UNSPECIFIED_TX_POWER_LEVEL =
std::numeric_limits<TXPowerLevel>::min();
bool is_connectable;
+2 -4
View File
@@ -10,11 +10,9 @@ namespace nearby {
// unbounded queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-
template <typename ConcreteSubmittableExecutor>
class MultiThreadExecutor
: public SubmittableExecutor<ConcreteSubmittableExecutor> {
class MultiThreadExecutor : public SubmittableExecutor {
public:
~MultiThreadExecutor() override {}
~MultiThreadExecutor() override = default;
};
} // namespace nearby
+106
View File
@@ -0,0 +1,106 @@
#ifndef PLATFORM_API_PLATFORM_H_
#define PLATFORM_API_PLATFORM_H_
#include <cstdint>
#include "platform/api/atomic_boolean.h"
#include "platform/api/atomic_reference_def.h"
#include "platform/api/ble.h"
#include "platform/api/ble_v2.h"
#include "platform/api/bluetooth_adapter.h"
#include "platform/api/bluetooth_classic.h"
#include "platform/api/condition_variable.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/hash_utils.h"
#include "platform/api/lock.h"
#include "platform/api/scheduled_executor.h"
#include "platform/api/server_sync.h"
#include "platform/api/settable_future_def.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/api/system_clock.h"
#include "platform/api/thread_utils.h"
//#include "platform/api/webrtc.h"
#include "platform/api/wifi.h"
#include "platform/api/wifi_lan.h"
// Project-specific basic types, that are not part of API.
// TODO(apolyudov): replace with c++ standard types.
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
// API rework notes:
// https://docs.google.com/spreadsheets/d/1erZNkX7pX8s5jWTHdxgjntxTMor3BGiY2H_fC_ldtoQ/edit#gid=381357998
class ImplementationPlatform {
public:
// Class Templates in platform code.
//
// Platform interface does not support templates directly.
// This is a design decision. The purpose is to have type isolation
// between platform library (or simply platform) and core library.
// Another goal is to make a platform implementation a black box,
// which does not leak implementation details in any form, be that types,
// methods, or variables.
//
// Core library code does provide platform-specific class templates
// on top of (a non-templated) platform support.
//
// For every common library template that needs platform support,
// platform must provide an absl::any specialization of class template:
template <typename T>
static Ptr<AtomicReference<T>> createAtomicReference(T initial_value = T{});
template <typename T>
static Ptr<SettableFuture<T>> createSettableFuture();
// AtomicReference<T>
static Ptr<AtomicReference<absl::any>> createAtomicReferenceAny(
absl::any initial_value);
// SettableFuture<T>
static Ptr<SettableFuture<absl::any>> createSettableFutureAny();
// Non-template methods: general platform support.
static Ptr<AtomicBoolean> createAtomicBoolean(bool initial_value);
static Ptr<CountDownLatch> createCountDownLatch(std::int32_t count);
static Ptr<Lock> createLock();
static Ptr<ConditionVariable> createConditionVariable(Ptr<Lock> lock);
static Ptr<HashUtils> createHashUtils();
static Ptr<ThreadUtils> createThreadUtils();
static Ptr<SystemClock> createSystemClock();
// Java-like Executors
// Type aliases used to API 1.0 compatibility.
// They will be retired soon.
// TODO(apolyudov): cleanup.
using SingleThreadExecutorType = SubmittableExecutor;
using MultiThreadExecutorType = SubmittableExecutor;
using ScheduledExecutorType = ScheduledExecutor;
static Ptr<SubmittableExecutor> createSingleThreadExecutor();
static Ptr<SubmittableExecutor> createMultiThreadExecutor(
std::int32_t max_concurrency);
static Ptr<ScheduledExecutor> createScheduledExecutor();
// Protocol implementations, domain-specific support
static Ptr<BluetoothAdapter> createBluetoothAdapter();
static Ptr<WifiMedium> createWifiMedium();
static Ptr<BluetoothClassicMedium> createBluetoothClassicMedium();
static Ptr<BLEMedium> createBLEMedium();
static Ptr<BLEMediumV2> createBLEMediumV2();
static Ptr<ServerSyncMedium> createServerSyncMedium();
static Ptr<WifiLanMedium> createWifiLanMedium();
// static Ptr<WebRtcSignalingMessenger> createWebRtcSignalingMessenger(
// const std::string& self_id);
static std::string getDeviceId();
static std::string getPayloadPath(int64_t payload_id);
};
} // namespace platform
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_PLATFORM_H_
+3 -3
View File
@@ -3,7 +3,7 @@
#include <cstdint>
#include "platform/api/executor.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/cancelable.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
@@ -15,9 +15,9 @@ namespace nearby {
// execute periodically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
class ScheduledExecutor : public Executor {
class ScheduledExecutor : public SubmittableExecutor {
public:
virtual ~ScheduledExecutor() {}
~ScheduledExecutor() override = default;
virtual Ptr<Cancelable> schedule(Ptr<Runnable> runnable,
std::int64_t delay_millis) = 0;
+1 -1
View File
@@ -22,7 +22,7 @@ class ServerSyncDevice {
virtual std::string getOwnGuid() = 0;
};
// Container of operations that can be performed over the Chrome Sync medium.
// Container of operations that can be performed over the Server Sync medium.
class ServerSyncMedium {
public:
virtual ~ServerSyncMedium() {}
+49 -8
View File
@@ -1,24 +1,65 @@
#ifndef PLATFORM_API_SETTABLE_FUTURE_H_
#define PLATFORM_API_SETTABLE_FUTURE_H_
#include "platform/api/listenable_future.h"
#include "platform/api/platform.h"
#include "platform/api/settable_future_def.h"
#include "platform/exception.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
// A SettableFuture is a type of Future whose result can be set.
//
// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
namespace platform {
namespace impl {
template <typename T>
class SettableFuture : public ListenableFuture<T> {
class SettableFutureImpl : public SettableFuture<T> {
public:
~SettableFuture() override {}
SettableFutureImpl() {
future_ = platform::ImplementationPlatform::createSettableFutureAny();
}
virtual bool set(T value) = 0;
~SettableFutureImpl() override = default;
virtual bool setException(Exception exception) = 0;
bool set(T value) override { return future_->set(absl::any(value)); }
bool setException(Exception exception) override {
return future_->setException(exception);
}
void addListener(Ptr<Runnable> runnable, Executor* executor) override {
future_->addListener(runnable, executor);
}
ExceptionOr<T> get() override { return CommonGet(future_->get()); }
ExceptionOr<T> get(std::int64_t timeout_ms) override {
return CommonGet(future_->get(timeout_ms));
}
private:
ExceptionOr<T> CommonGet(ExceptionOr<absl::any> ret_val) {
if (ret_val.exception() != Exception::kSuccess) {
return ExceptionOr<T>{ret_val.exception()};
}
return ExceptionOr<T>{absl::any_cast<T>(ret_val.result())};
}
Ptr<SettableFuture<absl::any>> future_;
};
} // namespace impl
template <typename T>
Ptr<SettableFuture<T>> ImplementationPlatform::createSettableFuture() {
return Ptr<SettableFuture<T>>(new impl::SettableFutureImpl<T>{});
}
} // namespace platform
} // namespace nearby
} // namespace location
+31
View File
@@ -0,0 +1,31 @@
#ifndef PLATFORM_API_SETTABLE_FUTURE_DEF_H_
#define PLATFORM_API_SETTABLE_FUTURE_DEF_H_
#include "platform/api/listenable_future.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// A SettableFuture is a type of Future whose result can be set.
//
// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
//
// Platform must implentent non-template static member functions
// Ptr<SettableFuture<size_t>> CreateSettableFutureSizeT()
// Ptr<SettableFuture<std::shared_ptr<void>>> CreateSettableFuturePtr()
// in the location::nearby::platform::ImplementationPlatform class.
template <typename T>
class SettableFuture : public ListenableFuture<T> {
public:
~SettableFuture() override = default;
virtual bool set(T value) = 0;
virtual bool setException(Exception exception) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SETTABLE_FUTURE_DEF_H_
+2 -4
View File
@@ -10,11 +10,9 @@ namespace nearby {
// queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--
template <typename ConcreteSubmittableExecutor>
class SingleThreadExecutor
: public SubmittableExecutor<ConcreteSubmittableExecutor> {
class SingleThreadExecutor : public SubmittableExecutor {
public:
~SingleThreadExecutor() override {}
~SingleThreadExecutor() override = default;
};
} // namespace nearby
+27 -24
View File
@@ -1,37 +1,40 @@
#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_H_
#include <functional>
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/callable.h"
#include "platform/port/down_cast.h"
#include "platform/ptr.h"
#include "platform/api/platform.h"
#include "platform/api/settable_future.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// Each per-platform concrete implementation is expected to extend from
// SubmittableExecutor and provide an override of its submit() method.
//
// e.g.
// class IOSSubmittableExecutor
// : public SubmittableExecutor<IOSSubmittableExecutor> {
// public:
// template <typename T>
// Ptr<Future<T> > submit(Ptr<Callable<T> > callable) {
// ...
// }
// }
template <typename ConcreteSubmittableExecutor>
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override {}
template <typename T>
Ptr<Future<T>> submit(Ptr<Callable<T>> callable) {
return DOWN_CAST<ConcreteSubmittableExecutor*>(this)->submit(callable);
// "Common" part of implementation.
// Placed here for textual compatibility to minimize scope of changes.
// Can be (and should be) moved to a separate file outside "api" folder.
// TODO(apolyudov): for API v2.0
template <typename T>
Ptr<Future<T>> SubmittableExecutor::submit(Ptr<Callable<T>> callable) {
using Platform = platform::ImplementationPlatform;
Ptr<SettableFuture<T>> future{Platform::createSettableFuture<T>()};
bool submitted = DoSubmit([callable, future]() {
ExceptionOr<T> result = callable->call();
if (result.ok()) {
future->set(std::move(result.result()));
} else {
future->setException({result.exception()});
}
});
if (!submitted) {
// Raise Exception::kExecution if we are shutting down.
future->setException({Exception::kExecution});
}
};
return future;
}
} // namespace nearby
} // namespace location
@@ -0,0 +1,35 @@
#ifndef PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
#define PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
#include <functional>
#include "platform/api/executor.h"
#include "platform/api/future.h"
#include "platform/callable.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// Main interface to be used by platform as a base class for
// - MultiThreadExecutorWrapper
// - SingleThreadExecutorWrapper
// Platform must override bool submit(std::function<void()>) method.
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override = default;
template <typename T>
Ptr<Future<T>> submit(Ptr<Callable<T>> callable);
protected:
// Submit a callable (with no delay).
// Returns true, if callable was submitted, false otherwise.
// Callable is not submitted if shutdown is in progress.
virtual bool DoSubmit(std::function<void()> wrapped_callable) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API_SUBMITTABLE_EXECUTOR_DEF_H_
+4 -3
View File
@@ -5,11 +5,11 @@
#include "platform/byte_array.h"
#include "platform/ptr.h"
#include "webrtc/files/stable/webrtc/api/peer_connection_interface.h"
//#include "webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
#if 0
class WebRtcSignalingMessenger {
public:
virtual ~WebRtcSignalingMessenger() = default;
@@ -33,12 +33,13 @@ class WebRtcSignalingMessenger {
virtual bool registerSignaling() = 0;
virtual bool unregisterSignaling() = 0;
virtual bool sendMessage(const string& peer_id,
virtual bool sendMessage(const std::string& peer_id,
ConstPtr<ByteArray> message) = 0;
virtual bool startReceivingMessages(
Ptr<SignalingMessageListener> listener) = 0;
virtual void getIceServers(Ptr<IceServersListener> ice_servers_listener) = 0;
};
#endif
} // namespace nearby
} // namespace location
+11 -9
View File
@@ -7,6 +7,7 @@
#include "platform/exception.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
@@ -50,9 +51,10 @@ class WifiLanMedium {
public:
virtual ~WifiLanMedium() = default;
virtual bool StartAdvertising(const std::string& service_id,
const string& wifi_lan_service_info_name) = 0;
virtual void StopAdvertising(const std::string& service_id) = 0;
virtual bool StartAdvertising(
absl::string_view service_id,
absl::string_view wifi_lan_service_info_name) = 0;
virtual void StopAdvertising(absl::string_view service_id) = 0;
// Callback for WifiLan discover results.
class DiscoveredServiceCallback {
@@ -64,9 +66,9 @@ class WifiLanMedium {
};
virtual bool StartDiscovery(
const std::string& service_id,
absl::string_view service_id,
Ptr<DiscoveredServiceCallback> discovered_service_callback) = 0;
virtual void StopDiscovery(const std::string& service_id) = 0;
virtual void StopDiscovery(absl::string_view service_id) = 0;
class AcceptedConnectionCallback {
public:
@@ -76,16 +78,16 @@ class WifiLanMedium {
// destroyed) by the recipient of the callback methods (i.e. the creator of
// the concrete AcceptedConnectionCallback object).
virtual void OnConnectionAccepted(Ptr<WifiLanSocket> socket,
const string& service_id) = 0;
absl::string_view service_id) = 0;
};
virtual bool StartAcceptingConnections(
const std::string& service_id,
absl::string_view service_id,
Ptr<AcceptedConnectionCallback> accepted_connection_callback) = 0;
virtual void StopAcceptingConnections(const std::string& service_id) = 0;
virtual void StopAcceptingConnections(absl::string_view service_id) = 0;
virtual Ptr<WifiLanSocket> Connect(Ptr<WifiLanService> wifi_lan_service,
const std::string& service_id) = 0;
absl::string_view service_id) = 0;
};
} // namespace nearby
-65
View File
@@ -1,65 +0,0 @@
package(default_visibility = [
"//core:__subpackages__",
"//platform:__subpackages__",
"//location/nearby/setup/core:__subpackages__",
])
cc_library(
name = "api2",
hdrs = [
"atomic_boolean.h",
"atomic_reference.h",
"ble.h",
"ble_v2.h",
"bluetooth_adapter.h",
"bluetooth_classic.h",
"condition_variable.h",
"count_down_latch.h",
"executor.h",
"future.h",
"hash_utils.h",
"input_file.h",
"input_stream.h",
"listenable_future.h",
"multi_thread_executor.h",
"mutex.h",
"output_file.h",
"output_stream.h",
"scheduled_executor.h",
"server_sync.h",
"settable_future.h",
"single_thread_executor.h",
"socket.h",
"submittable_executor.h",
"system_clock.h",
"thread_utils.h",
"webrtc.h",
"wifi.h",
],
deps = [
"//platform:types",
"//absl/strings",
"//absl/time",
"//webrtc/files/stable/webrtc/api:libjingle_peerconnection_api",
],
)
cc_library(
name = "mutex",
hdrs = ["mutex.h"],
visibility = [
"//platform:__subpackages__",
],
)
cc_library(
name = "condition_variable",
hdrs = ["condition_variable.h"],
visibility = [
"//platform:__subpackages__",
],
deps = [
"//platform:types",
"//absl/time",
],
)
-41
View File
@@ -1,41 +0,0 @@
add_library(platform_api2 STATIC)
target_sources(platform_api2
PUBLIC
atomic_boolean.h
atomic_reference.h
ble.h
ble_v2.h
bluetooth_adapter.h
bluetooth_classic.h
condition_variable.h
count_down_latch.h
executor.h
future.h
hash_utils.h
input_file.h
input_stream.h
listenable_future.h
multi_thread_executor.h
mutex.h
output_file.h
output_stream.h
scheduled_executor.h
server_sync.h
settable_future.h
single_thread_executor.h
socket.h
submittable_executor.h
system_clock.h
thread_utils.h
webrtc.h
wifi.h
)
target_link_libraries(platform_api2
PUBLIC
absl::strings
absl::time
platform_types
webrtc_api_libjingle_peerconnection_api
)
-21
View File
@@ -1,21 +0,0 @@
#ifndef PLATFORM_API2_ATOMIC_BOOLEAN_H_
#define PLATFORM_API2_ATOMIC_BOOLEAN_H_
namespace location {
namespace nearby {
// A boolean value that may be updated atomically.
//
// https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html
class AtomicBoolean {
public:
virtual ~AtomicBoolean() {}
virtual bool Get() = 0;
virtual void Set(bool value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_ATOMIC_BOOLEAN_H_
-22
View File
@@ -1,22 +0,0 @@
#ifndef PLATFORM_API2_ATOMIC_REFERENCE_H_
#define PLATFORM_API2_ATOMIC_REFERENCE_H_
namespace location {
namespace nearby {
// An object reference that may be updated atomically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html
template <typename T>
class AtomicReference {
public:
virtual ~AtomicReference() {}
virtual T Get() = 0;
virtual void Set(const T& value) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_ATOMIC_REFERENCE_H_
-111
View File
@@ -1,111 +0,0 @@
#ifndef PLATFORM_API2_BLE_H_
#define PLATFORM_API2_BLE_H_
#include "platform/api2/bluetooth_classic.h"
#include "platform/api2/input_stream.h"
#include "platform/api2/output_stream.h"
#include "platform/byte_array.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// Opaque wrapper over a BLE peripheral. Must contain enough data about a
// particular BLE device to connect to its GATT server.
class BlePeripheral {
public:
virtual ~BlePeripheral() {}
// The returned Ptr is not owned by the caller, and can be invalidated once
// the corresponding BLEPeripheral object is destroyed.
virtual BluetoothDevice& GetBluetoothDevice() = 0;
};
class BleSocket {
public:
virtual ~BleSocket() {}
// Returns the InputStream of the BleSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
virtual InputStream& GetInputStream() = 0;
// Returns the OutputStream of the BleSocket.
// On error, returned stream will report Exception::kIo on any operation.
//
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
virtual OutputStream& GetOutputStream() = 0;
// Conforms to the same contract as
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close().
//
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
// The returned object is not owned by the caller, and can be invalidated once
// the BleSocket object is destroyed.
virtual BlePeripheral& GetRemotePeripheral() = 0;
};
// Container of operations that can be performed over the BLE medium.
class BleMedium {
public:
virtual ~BleMedium() {}
virtual bool StartAdvertising(absl::string_view service_id,
const ByteArray& advertisement) = 0;
virtual void StopAdvertising(absl::string_view service_id) = 0;
class DiscoveredPeripheralCallback {
public:
virtual ~DiscoveredPeripheralCallback() {}
// The BlePeripheral* is not owned by callbacks.
// It is passed to give access to its non-const methods.
// It is guaranteed to be valid for the duration of call.
virtual void OnPeripheralDiscovered(BlePeripheral* ble_peripheral,
absl::string_view service_id,
const ByteArray& advertisement) = 0;
virtual void OnPeripheralLost(BlePeripheral* ble_peripheral,
absl::string_view service_id) = 0;
};
// Returns true once the BLE scan has been initiated.
virtual bool StartScanning(
absl::string_view service_id,
const DiscoveredPeripheralCallback& discovered_peripheral_callback) = 0;
// Returns true once BLE scanning for service_id is well and truly stopped;
// after this returns, there must be no more invocations of the
// DiscoveredPeripheralCallback passed in to StartScanning() for service_id.
virtual void StopScanning(absl::string_view service_id) = 0;
// Callback that is invoked when a new connection is accepted.
class AcceptedConnectionCallback {
public:
virtual ~AcceptedConnectionCallback() {}
virtual void OnConnectionAccepted(std::unique_ptr<BleSocket> socket,
absl::string_view service_id) = 0;
};
// Returns true once BLE socket connection requests to service_id can be
// accepted.
virtual bool StartAcceptingConnections(
absl::string_view service_id,
const AcceptedConnectionCallback& accepted_connection_callback) = 0;
virtual void StopAcceptingConnections(const std::string& service_id) = 0;
// BlePeripheral* is not owned by this call;
// it must remain valid for the duration of a call.
virtual std::unique_ptr<BleSocket> Connect(BlePeripheral* ble_peripheral,
absl::string_view service_id) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_BLE_H_
-390
View File
@@ -1,390 +0,0 @@
#ifndef PLATFORM_API2_BLE_V2_H_
#define PLATFORM_API2_BLE_V2_H_
#include <cstdint>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
namespace v2 {
// https://developer.android.com/reference/android/bluetooth/le/AdvertiseData
//
// Bundle of data found in a BLE advertisement.
//
// All service UUIDs will conform to the 16-bit Bluetooth base UUID,
// 0000xxxx-0000-1000-8000-00805F9B34FB. This makes it possible to store two
// byte service UUIDs in the advertisement.
struct BleAdvertisementData {
using TxPowerLevel = int8_t;
static const TxPowerLevel kUnspecifiedTxPowerLevel =
std::numeric_limits<TxPowerLevel>::min();
bool is_connectable;
// When set to kUnspecifiedTxPowerLevel, TX power should not be included in
// the advertisement data.
TxPowerLevel tx_power_level;
// When set to an empty string, local name should not be included in the
// advertisement data.
std::string local_name;
// When set to an empty vector, the set of 16-bit service class UUIDs should
// not be included in the advertisement data.
std::set<std::string> service_uuids;
// Maps service UUIDs to their service data.
std::map<std::string, ByteArray> service_data;
};
// Opaque wrapper over a BLE peripheral. Must be able to uniquely identify a
// peripheral so that we can connect to its GATT server.
class BlePeripheral {
public:
virtual ~BlePeripheral() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice#getAddress()
//
// This should be the MAC address when possible. If the implementation is
// unable to retrieve that, any unique identifier should suffice.
virtual std::string GetId() const = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic
//
// Representation of a GATT characteristic.
class GattCharacteristic {
public:
virtual ~GattCharacteristic() {}
// Possible permissions of a GATT characteristic.
enum class Permission {
kUnknown = 0,
kRead = 1,
kWrite = 2,
kLast,
};
// Possible properties of a GATT characteristic.
enum class Property {
kUnknown = 0,
kRead = 1,
kWrite = 2,
kIndicate = 3,
kLast,
};
// Returns the UUID of this characteristic.
virtual std::string GetUuid() = 0;
// Returns the UUID of the containing GATT service.
virtual std::string GetServiceUuid() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt
//
// Representation of a client GATT connection to a remote GATT server.
class ClientGattConnection {
public:
virtual ~ClientGattConnection() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getDevice()
//
// Retrieves the BLE peripheral that this connection is tied to.
virtual BlePeripheral& GetPeripheral() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()
//
// Discovers all available services and characteristics on this connection.
// Returns whether or not discovery finished successfully.
//
// This function should block until discovery has finished.
virtual bool DiscoverServices() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getService(java.util.UUID)
// https://developer.android.com/reference/android/bluetooth/BluetoothGattService.html#getCharacteristic(java.util.UUID)
//
// Retrieves a GATT characteristic. On error, does not return a value.
//
// DiscoverServices() should be called before this method to fetch all
// available services and characteristics first.
//
// It is okay for duplicate services to exist, as long as the specified
// characteristic UUID is unique among all services of the same UUID.
virtual std::optional<GattCharacteristic> GetCharacteristic(
absl::string_view service_uuid,
absl::string_view characteristic_uuid) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#readCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#getValue()
//
// Reads a GATT characteristic. No value is returned upon error.
virtual std::optional<ByteArray> ReadCharacteristic(
const GattCharacteristic& characteristic) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)
//
// Sends a remote characteristic write request to the server and returns
// whether or not it was successful.
virtual bool WriteCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#disconnect()
//
// Disconnects a GATT connection.
virtual void Disconnect() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
//
// Representation of a server GATT connection to a remote GATT client.
class ServerGattConnection {
public:
virtual ~ServerGattConnection() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#notifyCharacteristicChanged(android.bluetooth.BluetoothDevice,%20android.bluetooth.BluetoothGattCharacteristic,%20boolean)
//
// Sends a notification (via indication) to the client that a characteristic
// has changed with the given value. Returns whether or not it was successful.
//
// The value sent does not have to reflect the locally stored characteristic
// value. To update the local value, call GattServer::UpdateCharacteristic.
virtual bool SendCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
};
// Callback for asynchronous events on the client side of a GATT connection.
class ClientGattConnectionLifeCycleCallback {
public:
virtual ~ClientGattConnectionLifeCycleCallback() {}
// Called when the client is disconnected from the GATT server.
virtual void OnDisconnected(ClientGattConnection* connection) = 0;
};
// Callback for asynchronous events on the server side of a GATT connection.
class ServerGattConnectionLifeCycleCallback {
public:
virtual ~ServerGattConnectionLifeCycleCallback() {}
// Called when a remote peripheral connected to us and subscribed to one of
// our characteristics.
virtual void OnCharacteristicSubscription(
ServerGattConnection* connection,
const GattCharacteristic& characteristic) = 0;
// Called when a remote peripheral unsubscribed from one of our
// characteristics.
virtual void OnCharacteristicUnsubscription(
ServerGattConnection* connection,
const GattCharacteristic& characteristic) = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothGattServer
//
// Representation of a BLE GATT server.
class GattServer {
public:
virtual ~GattServer() {}
// Creates a characteristic and adds it to the GATT server under the given
// characteristic and service UUIDs. Returns no value upon error.
//
// Characteristics of the same service UUID should be put under one
// service rather than many services with the same UUID.
//
// If the INDICATE property is included, the characteristic should include the
// official Bluetooth Client Characteristic Configuration descriptor with UUID
// 0x2902 and a WRITE permission. This allows remote clients to write to this
// descriptor and subscribe for characteristic changes. For more information
// about this descriptor, please go to:
// https://www.bluetooth.com/specifications/Gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.Gatt.client_characteristic_configuration.xml
virtual std::optional<GattCharacteristic> CreateCharacteristic(
absl::string_view service_uuid, absl::string_view characteristic_uuid,
const std::set<GattCharacteristic::Permission>& permissions,
const std::set<GattCharacteristic::Property>& properties) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothGattCharacteristic.html#setValue(byte[])
//
// Locally updates the value of a characteristic and returns whether or not it
// was successful.
// Takes ownership of (and is responsible for destroying) the passed-in
// 'value'.
virtual bool UpdateCharacteristic(const GattCharacteristic& characteristic,
const ByteArray& value) = 0;
// Stops a GATT server.
virtual void Stop() = 0;
};
// A BLE socket representation.
class BleSocket {
public:
virtual ~BleSocket() {}
// Returns the remote BLE peripheral tied to this socket.
virtual BlePeripheral& GetRemotePeripheral() = 0;
// Writes a message on the socket and blocks until finished. Returns
// Exception::kIo upon error, and Exception::kSuccess otherwise.
virtual Exception Write(const ByteArray& message) = 0;
// Closes the socket and blocks until finished. Returns Exception::kIo upon
// error, and Exception::kSuccess otherwise.
virtual Exception Close() = 0;
};
// Callback for asynchronous events on a BleSocket object.
class BleSocketLifeCycleCallback {
public:
virtual ~BleSocketLifeCycleCallback() {}
// Called when a message arrives on a socket.
virtual void OnMessageReceived(BleSocket* socket,
const ByteArray& message) = 0;
// Called when a socket gets disconnected.
virtual void OnDisconnected(BleSocket* socket) = 0;
};
// Callback for asynchronous events on the server side of a BleSocket object.
class ServerBleSocketLifeCycleCallback : public BleSocketLifeCycleCallback {
public:
~ServerBleSocketLifeCycleCallback() override {}
// Called when a new incoming socket has been established.
virtual void OnSocketEstablished(BleSocket* socket) = 0;
};
// The main BLE medium used inside of Nearby. This serves as the entry point for
// all BLE and GATT related operations.
class BleMedium {
public:
using Mtu = uint32_t;
virtual ~BleMedium() {}
// Coarse representation of power settings throughout all BLE operations.
enum class PowerMode {
kUnknown = 0,
kLow = 1,
kHigh = 2,
kLast,
};
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#startAdvertising(android.bluetooth.le.AdvertiseSettings,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseData,%20android.bluetooth.le.AdvertiseCallback)
//
// Starts BLE advertising and returns whether or not it was successful.
//
// Power mode should be interpreted in the following way:
// LOW:
// - Advertising interval = ~1000ms
// - TX power = low
// HIGH:
// - Advertising interval = ~100ms
// - TX power = high
virtual bool StartAdvertising(const BleAdvertisementData& advertisement_data,
const BleAdvertisementData& scan_response,
PowerMode power_mode) = 0;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeAdvertiser.html#stopAdvertising(android.bluetooth.le.AdvertiseCallback)
//
// Stops advertising.
virtual void StopAdvertising() = 0;
// https://developer.android.com/reference/android/bluetooth/le/ScanCallback
//
// Callback for BLE scan results.
class ScanCallback {
public:
virtual ~ScanCallback() {}
// https://developer.android.com/reference/android/bluetooth/le/ScanCallback.html#onScanResult(int,%20android.bluetooth.le.ScanResult)
//
// Called when a BLE advertisement is discovered.
//
// The passed in advertisement_data is the merged combination of both
// advertisement data and scan response.
//
// Every discovery of an advertisement should be reported, even if the
// advertisement was discovered before.
//
// Ownership of the BleAdvertisementData transfers to the caller at this
// point.
virtual void OnAdvertisementFound(
BlePeripheral* peripheral,
const BleAdvertisementData& advertisement_data) = 0;
};
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#startScan(java.util.List%3Candroid.bluetooth.le.ScanFilter%3E,%20android.bluetooth.le.ScanSettings,%20android.bluetooth.le.ScanCallback)
//
// Starts scanning and returns whether or not it was successful.
//
// Power mode should be interpreted in the following way:
// LOW:
// - Scan window = ~512ms
// - Scan interval = ~5120ms
// HIGH:
// - Scan window = ~4096ms
// - Scan interval = ~4096ms
virtual bool StartScanning(const std::set<std::string>& service_uuids,
PowerMode power_mode,
const ScanCallback& scan_callback) = 0;
// https://developer.android.com/reference/android/bluetooth/le/BluetoothLeScanner.html#stopScan(android.bluetooth.le.ScanCallback)
//
// Stops scanning.
virtual void StopScanning() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothManager#openGattServer(android.content.Context,%20android.bluetooth.BluetoothGattServerCallback)
//
// Starts a GATT server. Returns a nullptr upon error.
virtual std::unique_ptr<GattServer> StartGattServer(
const ServerGattConnectionLifeCycleCallback& callback) = 0;
// Starts listening for incoming BLE sockets and returns false upon error.
virtual bool StartListeningForIncomingBleSockets(
const ServerBleSocketLifeCycleCallback& callback) = 0;
// Stops listening for incoming BLE sockets.
virtual void StopListeningForIncomingBleSockets() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback)
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestConnectionPriority(int)
// https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestMtu(int)
//
// Connects to a GATT server and negotiates the specified connection
// parameters. Returns nullptr upon error.
//
// Both connection interval and MTU can be negotiated on a best-effort basis.
//
// Power mode should be interpreted in the following way:
// LOW:
// - Connection interval = ~11.25ms - 15ms
// HIGH:
// - Connection interval = ~100ms - 125ms
virtual std::unique_ptr<ClientGattConnection> ConnectToGattServer(
BlePeripheral* peripheral, Mtu mtu, PowerMode power_mode,
const ClientGattConnectionLifeCycleCallback& callback) = 0;
// Establishes a BLE socket to the specified remote peripheral. Returns
// nullptr on error.
virtual std::unique_ptr<BleSocket> EstablishBleSocket(
BlePeripheral* peripheral,
const BleSocketLifeCycleCallback& callback) = 0;
};
} // namespace v2
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_BLE_V2_H_
-55
View File
@@ -1,55 +0,0 @@
#ifndef PLATFORM_API2_BLUETOOTH_ADAPTER_H_
#define PLATFORM_API2_BLUETOOTH_ADAPTER_H_
#include <cstdint>
#include <string>
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
class BluetoothAdapter {
public:
virtual ~BluetoothAdapter() {}
// Eligible statuses of the BluetoothAdapter.
enum class Status {
kDisabled,
kEnabled,
};
// Synchronously sets the status of the BluetoothAdapter to 'status', and
// returns true if the operation was a success.
virtual bool SetStatus(Status status) = 0;
// Returns true if the BluetoothAdapter's current status is
// Status::Value::kEnabled.
virtual bool IsEnabled() = 0;
// Scan modes of a BluetoothAdapter, as described at
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode().
enum class ScanMode {
kUnknown,
kConnectableDiscoverable,
};
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getScanMode()
//
// Returns ScanMode::kUnknown on error.
virtual ScanMode GetScanMode() = 0;
// Synchronously sets the scan mode of the adapter, and returns true if the
// operation was a success.
virtual bool SetScanMode(ScanMode scan_mode) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getName()
// Returns an empty string on error
virtual std::string GetName() const = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#setName(java.lang.String)
virtual bool SetName(absl::string_view name) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_BLUETOOTH_ADAPTER_H_
-124
View File
@@ -1,124 +0,0 @@
#ifndef PLATFORM_API2_BLUETOOTH_CLASSIC_H_
#define PLATFORM_API2_BLUETOOTH_CLASSIC_H_
#include <memory>
#include <string>
#include "platform/api2/input_stream.h"
#include "platform/api2/output_stream.h"
#include "platform/byte_array.h"
#include "platform/exception.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html.
class BluetoothDevice {
public:
virtual ~BluetoothDevice() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#getName()
virtual std::string GetName() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html.
class BluetoothSocket {
public:
virtual ~BluetoothSocket() {}
// Returns the InputStream of the BluetoothSocket.
virtual InputStream& GetInputStream() = 0;
// Returns the OutputStream of the BluetoothSocket.
virtual OutputStream& GetOutputStream() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#close()
//
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#getRemoteDevice()
virtual BluetoothDevice& GetRemoteDevice() = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html.
class BluetoothServerSocket {
public:
virtual ~BluetoothServerSocket() {}
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#accept()
//
// returns Exception::kIo on error.
virtual ExceptionOr<std::unique_ptr<BluetoothSocket>> Accept() = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html#close()
//
// Returns Exception::kIo on error, Exception::kSuccess otherwise.
virtual Exception Close() = 0;
};
// Container of operations that can be performed over the Bluetooth Classic
// medium.
class BluetoothClassicMedium {
public:
virtual ~BluetoothClassicMedium() {}
class DiscoveryCallback {
public:
virtual ~DiscoveryCallback() {}
// BluetoothDevice* is not owned by callbacks.
// Pointer is guaranteed to remain valid for the duration of a call.
virtual void OnDeviceDiscovered(BluetoothDevice* device) = 0;
virtual void OnDeviceNameChanged(BluetoothDevice* device) = 0;
virtual void OnDeviceLost(BluetoothDevice* device) = 0;
};
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()
//
// Returns true once the process of discovery has been initiated.
//
// Does not take ownership of the passed-in discovery_callback -- destroying
// that is up to the caller.
virtual bool StartDiscovery(const DiscoveryCallback& discovery_callback) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#cancelDiscovery()
//
// Returns true once discovery is well and truly stopped; after this returns,
// there must be no more invocations of the DiscoveryCallback passed in to
// startDiscovery().
virtual bool StopDiscovery() = 0;
// A combination of
// https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord
// followed by
// https://developer.android.com/reference/android/bluetooth/BluetoothSocket.html#connect().
//
// service_uuid is the canonical textual representation
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
// type 3 name-based
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// On success, returns a new BluetoothSocket, wrapped in a ExceptionOr object.
// On error, returns Exception object.
virtual ExceptionOr<std::unique_ptr<BluetoothSocket>> ConnectToService(
BluetoothDevice* remote_device, absl::string_view service_uuid) = 0;
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#listenUsingInsecureRfcommWithServiceRecord
//
// service_uuid is the canonical textual representation
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Format) of a
// type 3 name-based
// (https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based))
// UUID.
//
// Returns Exception::kIo on error.
virtual ExceptionOr<std::unique_ptr<BluetoothServerSocket>> ListenForService(
absl::string_view service_name, absl::string_view service_uuid) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_BLUETOOTH_CLASSIC_H_
-26
View File
@@ -1,26 +0,0 @@
#ifndef PLATFORM_API2_CONDITION_VARIABLE_H_
#define PLATFORM_API2_CONDITION_VARIABLE_H_
#include "platform/exception.h"
namespace location {
namespace nearby {
// The ConditionVariable class is a synchronization primitive that can be used
// to block a thread, or multiple threads at the same time, until another thread
// both modifies a shared variable (the condition), and notifies the
// ConditionVariable.
class ConditionVariable {
public:
virtual ~ConditionVariable() {}
// https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify--
virtual void Notify() = 0;
// https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--
virtual Exception Wait() = 0; // throws Exception::kInterrupted
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_CONDITION_VARIABLE_H_
-29
View File
@@ -1,29 +0,0 @@
#ifndef PLATFORM_API2_COUNT_DOWN_LATCH_H_
#define PLATFORM_API2_COUNT_DOWN_LATCH_H_
#include <cstdint>
#include "platform/exception.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
// A synchronization aid that allows one or more threads to wait until a set of
// operations being performed in other threads completes.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html
class CountDownLatch {
public:
virtual ~CountDownLatch() {}
virtual Exception Await() = 0; // throws Exception::kInterrupted
virtual ExceptionOr<bool> Await(
absl::Duration timeout) = 0; // throws Exception::kInterrupted
virtual void CountDown() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_COUNT_DOWN_LATCH_H_
-26
View File
@@ -1,26 +0,0 @@
#ifndef PLATFORM_API2_EXECUTOR_H_
#define PLATFORM_API2_EXECUTOR_H_
#include <memory>
#include "platform/runnable.h"
namespace location {
namespace nearby {
// This abstract class is the superclass of all classes representing an
// Executor.
class Executor {
public:
virtual ~Executor() = default;
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-
virtual void Execute(std::unique_ptr<Runnable> runnable) = 0;
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#shutdown--
virtual void Shutdown() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_EXECUTOR_H_
-30
View File
@@ -1,30 +0,0 @@
#ifndef PLATFORM_API2_FUTURE_H_
#define PLATFORM_API2_FUTURE_H_
#include "platform/exception.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
// A Future represents the result of an asynchronous computation.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html
template <typename T>
class Future {
public:
virtual ~Future() = default;
// throws Exception::kInterrupted, Exception::kExecution
virtual ExceptionOr<T> Get() = 0;
// throws Exception::kInterrupted, Exception::kExecution
// throws Exception::kTimeout if timeout is exceeded while waiting for
// result.
virtual ExceptionOr<T> Get(absl::Duration timeout) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_FUTURE_H_
-20
View File
@@ -1,20 +0,0 @@
#ifndef PLATFORM_API2_HASH_UTILS_H_
#define PLATFORM_API2_HASH_UTILS_H_
#include "platform/byte_array.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// A provider of standard hashing algorithms.
class HashUtils {
public:
static ByteArray Md5(absl::string_view input);
static ByteArray Sha256(absl::string_view input);
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_HASH_UTILS_H_
-24
View File
@@ -1,24 +0,0 @@
#ifndef PLATFORM_API2_INPUT_FILE_H_
#define PLATFORM_API2_INPUT_FILE_H_
#include <cstdint>
#include "platform/api2/input_stream.h"
#include "platform/byte_array.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// An InputFile represents a readable file on the system.
class InputFile : public InputStream {
public:
~InputFile() override = default;
virtual std::string GetFilePath() const = 0;
virtual size_t GetTotalSize() const = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_INPUT_FILE_H_
-27
View File
@@ -1,27 +0,0 @@
#ifndef PLATFORM_API2_INPUT_STREAM_H_
#define PLATFORM_API2_INPUT_STREAM_H_
#include <cstdint>
#include "platform/byte_array.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// An InputStream represents an input stream of bytes.
//
// https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
class InputStream {
public:
virtual ~InputStream() {}
virtual ExceptionOr<ByteArray> Read(
size_t size) = 0; // throws Exception::kIo
virtual Exception Close() = 0; // throws Exception::kIo
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_INPUT_STREAM_H_
-29
View File
@@ -1,29 +0,0 @@
#ifndef PLATFORM_API2_LISTENABLE_FUTURE_H_
#define PLATFORM_API2_LISTENABLE_FUTURE_H_
#include <memory>
#include "platform/api2/executor.h"
#include "platform/api2/future.h"
#include "platform/exception.h"
#include "platform/runnable.h"
namespace location {
namespace nearby {
// A Future that accepts completion listeners.
//
// https://guava.dev/releases/20.0/api/docs/com/google/common/util/concurrent/ListenableFuture.html
template <typename T>
class ListenableFuture : public Future<T> {
public:
~ListenableFuture() override = default;
virtual void AddListener(std::unique_ptr<Runnable> runnable,
Executor* executor) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_LISTENABLE_FUTURE_H_
-23
View File
@@ -1,23 +0,0 @@
#ifndef PLATFORM_API2_MULTI_THREAD_EXECUTOR_H_
#define PLATFORM_API2_MULTI_THREAD_EXECUTOR_H_
#include "platform/api2/submittable_executor.h"
namespace location {
namespace nearby {
// An Executor that reuses a fixed number of threads operating off a shared
// unbounded queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-
template <typename ConcreteSubmittableExecutor>
class MultiThreadExecutor
: public SubmittableExecutor<ConcreteSubmittableExecutor> {
public:
~MultiThreadExecutor() override {}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_MULTI_THREAD_EXECUTOR_H_
-22
View File
@@ -1,22 +0,0 @@
#ifndef PLATFORM_API2_MUTEX_H_
#define PLATFORM_API2_MUTEX_H_
namespace location {
namespace nearby {
// A lock is a tool for controlling access to a shared resource by multiple
// threads.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Lock.html
class Mutex {
public:
virtual ~Mutex() {}
virtual void Lock() = 0;
virtual void Unlock() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_MUTEX_H_
-20
View File
@@ -1,20 +0,0 @@
#ifndef PLATFORM_API2_OUTPUT_FILE_H_
#define PLATFORM_API2_OUTPUT_FILE_H_
#include "platform/api2/output_stream.h"
#include "platform/byte_array.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// An OutputFile represents a writable file on the system.
class OutputFile : public OutputStream {
public:
~OutputFile() override = default;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_OUTPUT_FILE_H_
-25
View File
@@ -1,25 +0,0 @@
#ifndef PLATFORM_API2_OUTPUT_STREAM_H_
#define PLATFORM_API2_OUTPUT_STREAM_H_
#include "platform/byte_array.h"
#include "platform/exception.h"
namespace location {
namespace nearby {
// An OutputStream represents an output stream of bytes.
//
// https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html
class OutputStream {
public:
virtual ~OutputStream() {}
virtual Exception Write(const ByteArray& data) = 0; // throws Exception::kIo
virtual Exception Flush() = 0; // throws Exception::kIo
virtual Exception Close() = 0; // throws Exception::kIo
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_OUTPUT_STREAM_H_
-29
View File
@@ -1,29 +0,0 @@
#ifndef PLATFORM_API2_SCHEDULED_EXECUTOR_H_
#define PLATFORM_API2_SCHEDULED_EXECUTOR_H_
#include <cstdint>
#include <memory>
#include "platform/api2/executor.h"
#include "platform/cancelable.h"
#include "platform/runnable.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
// An Executor that can schedule commands to run after a given delay, or to
// execute periodically.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
class ScheduledExecutor : public Executor {
public:
~ScheduledExecutor() override = default;
virtual std::unique_ptr<Cancelable> Schedule(
std::unique_ptr<Runnable> runnable, absl::Duration duration) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SCHEDULED_EXECUTOR_H_
-60
View File
@@ -1,60 +0,0 @@
#ifndef PLATFORM_API2_SERVER_SYNC_H_
#define PLATFORM_API2_SERVER_SYNC_H_
#include <string>
#include "platform/byte_array.h"
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// Abstraction that represents a Nearby endpoint exchanging data through
// ServerSync Medium.
class ServerSyncDevice {
public:
virtual ~ServerSyncDevice() = default;
virtual std::string GetName() const = 0;
virtual std::string GetGuid() const = 0;
virtual std::string GetOwnGuid() const = 0;
};
// Container of operations that can be performed over the Chrome Sync medium.
class ServerSyncMedium {
public:
virtual ~ServerSyncMedium() = default;
virtual bool StartAdvertising(absl::string_view service_id,
absl::string_view endpoint_id,
const ByteArray& endpoint_info) = 0;
virtual void StopAdvertising(absl::string_view service_id) = 0;
class DiscoveredDeviceCallback {
public:
virtual ~DiscoveredDeviceCallback() = default;
// Called on a new ServerSyncDevice discovery.
virtual void OnDeviceDiscovered(ServerSyncDevice* device,
absl::string_view service_id,
absl::string_view endpoint_id,
const ByteArray& endpoint_info) = 0;
// Called when ServerSyncDevice is no longer reachable.
virtual void OnDeviceLost(ServerSyncDevice* device,
absl::string_view service_id) = 0;
};
// Returns true once the Chrome Sync scan has been initiated.
virtual bool StartDiscovery(
absl::string_view service_id,
const DiscoveredDeviceCallback& discovered_device_callback) = 0;
// Returns true once Chrome Sync scan for service_id is well and truly
// stopped; after this returns, there must be no more invocations of the
// DiscoveredDeviceCallback passed in to startScanning() for service_id.
virtual void StopDiscovery(absl::string_view service_id) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SERVER_SYNC_H_
-24
View File
@@ -1,24 +0,0 @@
#ifndef PLATFORM_API2_SETTABLE_FUTURE_H_
#define PLATFORM_API2_SETTABLE_FUTURE_H_
#include "platform/api2/listenable_future.h"
namespace location {
namespace nearby {
// A SettableFuture is a type of Future whose result can be set.
//
// https://google.github.io/guava/releases/20.0/api/docs/com/google/common/util/concurrent/SettableFuture.html
template <typename T>
class SettableFuture : public ListenableFuture<T> {
public:
~SettableFuture() override = default;
virtual bool Set(const T& value) = 0;
virtual bool SetException(Exception exception) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SETTABLE_FUTURE_H_
@@ -1,23 +0,0 @@
#ifndef PLATFORM_API2_SINGLE_THREAD_EXECUTOR_H_
#define PLATFORM_API2_SINGLE_THREAD_EXECUTOR_H_
#include "platform/api2/submittable_executor.h"
namespace location {
namespace nearby {
// An Executor that uses a single worker thread operating off an unbounded
// queue.
//
// https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--
template <typename ConcreteSubmittableExecutor>
class SingleThreadExecutor
: public SubmittableExecutor<ConcreteSubmittableExecutor> {
public:
~SingleThreadExecutor() override {}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SINGLE_THREAD_EXECUTOR_H_
-25
View File
@@ -1,25 +0,0 @@
#ifndef PLATFORM_API2_SOCKET_H_
#define PLATFORM_API2_SOCKET_H_
#include "platform/api2/input_stream.h"
#include "platform/api2/output_stream.h"
namespace location {
namespace nearby {
// A socket is an endpoint for communication between two machines.
//
// https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html
class Socket {
public:
virtual ~Socket() {}
virtual InputStream& GetInputStream() = 0;
virtual OutputStream& GetOutputStream() = 0;
virtual void Close() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SOCKET_H_
-42
View File
@@ -1,42 +0,0 @@
#ifndef PLATFORM_API2_SUBMITTABLE_EXECUTOR_H_
#define PLATFORM_API2_SUBMITTABLE_EXECUTOR_H_
#include <memory>
#include "platform/api2/executor.h"
#include "platform/api2/future.h"
#include "platform/callable.h"
namespace location {
namespace nearby {
// Each per-platform concrete implementation is expected to extend from
// SubmittableExecutor and provide an override of its submit() method.
//
// e.g.
// class XyzSubmittableExecutor
// : public SubmittableExecutor<XyzSubmittableExecutor> {
// public:
// template <typename T>
// std::unique_ptr<Future<T>> submit(std::unique_ptr<Callable<T>> callable) {
// ...
// }
// }
template <typename ConcreteSubmittableExecutor>
class SubmittableExecutor : public Executor {
public:
~SubmittableExecutor() override {}
template <typename T>
std::unique_ptr<Future<T>> Submit(std::unique_ptr<Callable<T>> callable) {
static_assert(
std::is_base_of_v<SubmittableExecutor, ConcreteSubmittableExecutor>,
"Class template type is not derived from SubmittableExecutor");
return static_cast<ConcreteSubmittableExecutor*>(this)->submit(callable);
}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SUBMITTABLE_EXECUTOR_H_
-22
View File
@@ -1,22 +0,0 @@
#ifndef PLATFORM_API2_SYSTEM_CLOCK_H_
#define PLATFORM_API2_SYSTEM_CLOCK_H_
#include <cstdint>
#include "absl/time/time.h"
namespace location {
namespace nearby {
class SystemClock final {
public:
// Returns the time (in milliseconds) since the system was booted, and
// includes deep sleep. This clock should be guaranteed to be monotonic, and
// should continue to tick even when the CPU is in power saving modes.
static absl::Time ElapsedRealtime();
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_SYSTEM_CLOCK_H_
-22
View File
@@ -1,22 +0,0 @@
#ifndef PLATFORM_API2_THREAD_UTILS_H_
#define PLATFORM_API2_THREAD_UTILS_H_
#include <cstdint>
#include "platform/exception.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
class ThreadUtils final {
public:
// https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)
// throws Exception::kInterrupted
static Exception Sleep(absl::Duration timeout);
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_THREAD_UTILS_H_
-46
View File
@@ -1,46 +0,0 @@
#ifndef PLATFORM_API2_WEBRTC_H_
#define PLATFORM_API2_WEBRTC_H_
#include <vector>
#include "platform/byte_array.h"
#include "webrtc/files/stable/webrtc/api/peer_connection_interface.h"
namespace location {
namespace nearby {
class WebRtcSignalingMessenger {
public:
virtual ~WebRtcSignalingMessenger() = default;
/** Called whenever we receive an inbox message from tachyon. */
class SignalingMessageListener {
public:
virtual ~SignalingMessageListener() = default;
virtual void OnSignalingMessage(const ByteArray& message) = 0;
};
class IceServersListener {
public:
virtual ~IceServersListener() = default;
virtual void OnIceServersFetched(
std::vector<webrtc::PeerConnectionInterface::IceServer>
ice_servers) = 0;
};
virtual bool RegisterSignaling() = 0;
virtual bool UnregisterSignaling() = 0;
virtual bool SendMessage(std::string_view peer_id,
const ByteArray& message) = 0;
virtual bool StartReceivingMessages(
const SignalingMessageListener& listener) = 0;
virtual void GetIceServers(
const IceServersListener& ice_servers_listener) = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_WEBRTC_H_
-88
View File
@@ -1,88 +0,0 @@
#ifndef PLATFORM_API2_WIFI_H_
#define PLATFORM_API2_WIFI_H_
#include <cstdint>
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
namespace location {
namespace nearby {
// Possible authentication types for a WiFi network.
enum class WifiAuthType {
// WiFi Authentication type; either none (non-secured a.k.a. open) link, or
// WPA PSK (WiFi Protected Access PreShared Key), or
// see https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access
// WEP (Wired Equivalent Privacy);
// see https://en.wikipedia.org/wiki/Wired_Equivalent_Privacy
kUnknown = 0,
kOpen = 1,
kWpaPsk = 2,
kWep = 3,
};
// Possible statuses of a device's connection to a WiFi network.
enum class WifiConnectionStatus {
kUnknown = 0,
kConnected = 1,
kConnectionFailure = 2,
kAuthFailure = 3,
};
// Represents a WiFi network found during a call to WifiMedium#scan().
class WifiScanResult {
public:
virtual ~WifiScanResult() {}
// Gets the SSID of this WiFi network.
virtual std::string GetSsid() const = 0;
// Gets the signal strength of this WiFi network in dBm.
virtual std::int32_t GetSignalStrengthDbm() const = 0;
// Gets the frequency band of this WiFi network in MHz.
virtual std::int32_t GetFrequencyMhz() const = 0;
// Gets the authentication type of this WiFi network.
virtual WifiAuthType GetAuthType() const = 0;
};
// Container of operations that can be performed over the WiFi medium.
class WifiMedium {
public:
virtual ~WifiMedium() {}
class ScanResultCallback {
public:
virtual ~ScanResultCallback() {}
virtual void OnScanResults(
const std::vector<WifiScanResult>& scan_results) = 0;
};
// Does not take ownership of the passed-in scan_result_callback -- destroying
// that is up to the caller.
virtual bool Scan(const ScanResultCallback& scan_result_callback) = 0;
// If 'password' is an empty string, none has been provided. Returns
// WifiConnectionStatus::CONNECTED on success, or the appropriate failure code
// otherwise.
virtual WifiConnectionStatus ConnectToNetwork(absl::string_view ssid,
absl::string_view password,
WifiAuthType auth_type) = 0;
// Blocks until it's certain of there being a connection to the internet, or
// returns false if it fails to do so.
//
// How this method wants to verify said connection is totally up to it (so it
// can feel free to ping whatever server, download whatever resource, etc.
// that it needs to gain confidence that the internet is reachable hereon in).
virtual bool VerifyInternetConnectivity() = 0;
// Returns the local device's IP address in the IPv4 dotted-quad format.
virtual std::string GetIpAddress() = 0;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_API2_WIFI_H_
+80
View File
@@ -0,0 +1,80 @@
#include "platform/api/atomic_reference.h"
#include "platform/api/platform.h"
#include "platform/ptr.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace location {
namespace nearby {
namespace {
struct BigSizedStruct {
int data[100]{};
};
enum TestEnum {
kValue1 = 1,
kValue2 = 2,
};
enum class ScopedTestEnum {
kValue1 = 1,
kValue2 = 2,
};
bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
}
bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
return !(a == b);
}
} // namespace
TEST(AtomicReferenceTest, SupportIntegralTypes) {
auto p = platform::ImplementationPlatform::createAtomicReference<int>();
p->set(5);
ASSERT_EQ(p->get(), 5);
}
TEST(AtomicReferenceTest, SupportEnum) {
auto p = platform::ImplementationPlatform::createAtomicReference<TestEnum>();
p->set(TestEnum::kValue1);
ASSERT_EQ(p->get(), TestEnum::kValue1);
}
TEST(AtomicReferenceTest, SupportScopedEnum) {
auto p =
platform::ImplementationPlatform::createAtomicReference<ScopedTestEnum>();
p->set(ScopedTestEnum::kValue1);
ASSERT_EQ(p->get(), ScopedTestEnum::kValue1);
}
TEST(AtomicReferenceTest, SetTakesCopyOfValue) {
// Default constructor is zero-initalizing all data in BigSizedStruct.
BigSizedStruct v1;
auto p = platform::ImplementationPlatform::createAtomicReference<
BigSizedStruct>();
v1.data[0] = 5; // Changing value before calling set() will affect stored
v1.data[7] = 3; // value.
p->set(v1);
v1.data[1] = 6; // Changing value after calling set() will not affect stored
v1.data[5] = 4; // value.
BigSizedStruct v2 = p->get();
ASSERT_NE(v1, v2);
v1.data[1] = 0;
v1.data[5] = 0;
ASSERT_EQ(v2, v1);
}
TEST(AtomicReferenceTest, SupportObjects) {
std::string s{"test"};
auto ref =
platform::ImplementationPlatform::createAtomicReference<std::string>(s);
ASSERT_EQ(s, ref->get());
}
} // namespace nearby
} // namespace location
+1 -1
View File
@@ -37,7 +37,7 @@ class ByteArray {
data_.assign(size, value);
}
char* getData() { return data_.data(); }
char* getData() { return &data_[0]; }
const char* getData() const { return data_.data(); }
size_t size() const { return data_.size(); }
+12 -10
View File
@@ -1,25 +1,27 @@
#include "platform/cancelable_alarm.h"
#include "platform/api/platform.h"
#include "platform/api/scheduled_executor.h"
#include "platform/synchronized.h"
namespace location {
namespace nearby {
template <typename Platform>
CancelableAlarm<Platform>::CancelableAlarm(
const string &name, Ptr<Runnable> runnable, std::int64_t delay_millis,
Ptr<typename Platform::ScheduledExecutorType> scheduled_executor)
namespace {
using Platform = platform::ImplementationPlatform;
}
CancelableAlarm::CancelableAlarm(const std::string &name,
Ptr<Runnable> runnable,
std::int64_t delay_millis,
Ptr<ScheduledExecutor> scheduled_executor)
: name_(name),
lock_(Platform::createLock()),
cancelable_(scheduled_executor->schedule(runnable, delay_millis)) {}
template <typename Platform>
CancelableAlarm<Platform>::~CancelableAlarm() {
cancelable_.destroy();
}
CancelableAlarm::~CancelableAlarm() { cancelable_.destroy(); }
template <typename Platform>
bool CancelableAlarm<Platform>::cancel() {
bool CancelableAlarm::cancel() {
Synchronized s(lock_.get());
if (cancelable_.isNull()) {
+5 -7
View File
@@ -4,6 +4,7 @@
#include <cstdint>
#include "platform/api/lock.h"
#include "platform/api/scheduled_executor.h"
#include "platform/cancelable.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
@@ -17,18 +18,17 @@ namespace nearby {
* for posting a Runnable on a ScheduledExecutor and (possibly) later
* canceling it.
*/
template <typename Platform>
class CancelableAlarm {
public:
CancelableAlarm(
const string& name, Ptr<Runnable> runnable, std::int64_t delay_millis,
Ptr<typename Platform::ScheduledExecutorType> scheduled_executor);
CancelableAlarm(const std::string& name, Ptr<Runnable> runnable,
std::int64_t delay_millis,
Ptr<ScheduledExecutor> scheduled_executor);
~CancelableAlarm();
bool cancel();
private:
string name_;
std::string name_;
ScopedPtr<Ptr<Lock> > lock_;
Ptr<Cancelable> cancelable_;
};
@@ -36,6 +36,4 @@ class CancelableAlarm {
} // namespace nearby
} // namespace location
#include "platform/cancelable_alarm.cc"
#endif // PLATFORM_CANCELABLE_ALARM_H_
+4 -4
View File
@@ -15,13 +15,13 @@ struct Exception {
EXECUTION,
// New code should use the kConstants.
// Old CONSTANTS are deprecated, and should not be used.
kFailed = -1, // Initial value of Exception; any unknown error.
kFailed = -1, // Initial value of Exception; any unknown error.
kSuccess = NONE, // No exception.
kIo = IO, // IO Error happened.
kIo = IO, // IO Error happened.
kInterrupted = INTERRUPTED, // Operation was interrupted.
kInvalidProtocolBuffer = INVALID_PROTOCOL_BUFFER, // Couldn't parse.
kExecution = EXECUTION, // Couldn't execute.
kTimeout, // Operarion did not finish within specified time.
kExecution = EXECUTION, // Couldn't execute.
kTimeout, // Operation did not finish within specified time.
};
Value value {kFailed};
};
+1 -1
View File
@@ -14,7 +14,7 @@ namespace nearby {
class InputFileImpl final : public InputFile {
public:
explicit InputFileImpl(const std::string& path, std::int64_t size);
InputFileImpl(const std::string& path, std::int64_t size);
~InputFileImpl() override {}
ExceptionOr<ConstPtr<ByteArray>> read(std::int64_t size) override;
+1 -1
View File
@@ -42,7 +42,7 @@ class FileImplTest : public ::testing::Test {
ASSERT_TRUE(bytes.result().isNull());
}
static const int64_t kMaxSize = 3;
static constexpr int64_t kMaxSize = 3;
std::string path_;
std::fstream file_;
-45
View File
@@ -1,45 +0,0 @@
cc_library(
name = "default",
srcs = [
"default_platform.cc",
],
hdrs = [
"default_condition_variable.h",
"default_lock.h",
"default_platform.h",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core:__subpackages__",
],
deps = [
":condition_variable",
":lock",
"//platform:types",
"//platform/api",
],
)
cc_library(
name = "lock",
srcs = ["default_lock.cc"],
hdrs = ["default_lock.h"],
visibility = [
"//platform:__subpackages__",
],
deps = ["//platform/api:lock"],
)
cc_library(
name = "condition_variable",
srcs = ["default_condition_variable.cc"],
hdrs = ["default_condition_variable.h"],
visibility = [
"//platform:__subpackages__",
],
deps = [
":lock",
"//platform:types",
"//platform/api:condition_variable",
],
)
-51
View File
@@ -1,51 +0,0 @@
add_library(platform_impl_default STATIC)
target_sources(platform_impl_default
PRIVATE
default_platform.cc
PUBLIC
default_platform.h
)
target_include_directories(platform_impl_default
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(platform_impl_default
PUBLIC
platform_api
platform_impl_default_cond_var
platform_impl_default_lock
platform_types
)
add_library(platform_impl_default_lock STATIC)
target_sources(platform_impl_default_lock
PRIVATE
default_lock.cc
PUBLIC
default_lock.h
)
target_link_libraries(platform_impl_default_lock
PUBLIC
platform_api
)
add_library(platform_impl_default_cond_var STATIC)
target_sources(platform_impl_default_cond_var
PRIVATE
default_condition_variable.cc
PUBLIC
default_condition_variable.h
)
target_link_libraries(platform_impl_default_cond_var
PUBLIC
platform_api
platform_impl_default_lock
platform_types
)
@@ -1,28 +0,0 @@
#include "platform/impl/default/default_condition_variable.h"
namespace location {
namespace nearby {
DefaultConditionVariable::DefaultConditionVariable(Ptr<DefaultLock> lock)
: lock_(lock), attr_(), cond_() {
pthread_condattr_init(&attr_);
pthread_cond_init(&cond_, &attr_);
}
DefaultConditionVariable::~DefaultConditionVariable() {
pthread_cond_destroy(&cond_);
pthread_condattr_destroy(&attr_);
}
void DefaultConditionVariable::notify() { pthread_cond_broadcast(&cond_); }
Exception::Value DefaultConditionVariable::wait() {
pthread_cond_wait(&cond_, &(lock_->mutex_));
return Exception::NONE;
}
} // namespace nearby
} // namespace location
@@ -1,30 +0,0 @@
#ifndef PLATFORM_IMPL_DEFAULT_DEFAULT_CONDITION_VARIABLE_H_
#define PLATFORM_IMPL_DEFAULT_DEFAULT_CONDITION_VARIABLE_H_
#include <pthread.h>
#include "platform/api/condition_variable.h"
#include "platform/impl/default/default_lock.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
class DefaultConditionVariable : public ConditionVariable {
public:
explicit DefaultConditionVariable(Ptr<DefaultLock> lock);
~DefaultConditionVariable() override;
void notify() override;
Exception::Value wait() override;
private:
Ptr<DefaultLock> lock_;
pthread_condattr_t attr_;
pthread_cond_t cond_;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_DEFAULT_DEFAULT_CONDITION_VARIABLE_H_
@@ -1,17 +0,0 @@
#include "platform/impl/default/default_platform.h"
#include "platform/impl/default/default_condition_variable.h"
#include "platform/impl/default/default_lock.h"
namespace location {
namespace nearby {
Ptr<Lock> DefaultPlatform::createLock() { return MakePtr(new DefaultLock()); }
Ptr<ConditionVariable> DefaultPlatform::createConditionVariable(
Ptr<Lock> lock) {
return MakePtr(new DefaultConditionVariable(DowncastPtr<DefaultLock>(lock)));
}
} // namespace nearby
} // namespace location
@@ -1,26 +0,0 @@
#ifndef PLATFORM_IMPL_DEFAULT_DEFAULT_PLATFORM_H_
#define PLATFORM_IMPL_DEFAULT_DEFAULT_PLATFORM_H_
#include "platform/api/condition_variable.h"
#include "platform/api/lock.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
// Provides obvious portable implementations of a subset of the hooks specified
// within //platform/api/.
//
// It's highly recommended that custom Platform implementations delegate to
// these methods unless there's a very good reason not to.
class DefaultPlatform {
public:
static Ptr<Lock> createLock();
static Ptr<ConditionVariable> createConditionVariable(Ptr<Lock> lock);
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_DEFAULT_DEFAULT_PLATFORM_H_
+26
View File
@@ -0,0 +1,26 @@
cc_library(
name = "g3",
srcs = [
"atomic_reference_impl.h",
"platform.cc",
"settable_future_impl.h",
"system_clock_impl.h",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core:__subpackages__",
"//platform:__subpackages__",
],
deps = [
"//platform:types",
"//platform/api",
"//platform/impl/shared:atomic_boolean",
"//platform/impl/shared:posix_condition_variable",
"//platform/impl/shared:posix_lock",
"//platform/port:string",
"//absl/base:core_headers",
"//absl/synchronization",
"//absl/time",
"//absl/types:any",
],
)
+27
View File
@@ -0,0 +1,27 @@
add_library(platform_impl_g3 STATIC)
target_sources(platform_impl_g3
PRIVATE
"atomic_reference_impl.h"
"platform.cc"
"settable_future_impl.h"
"system_clock_impl.h"
)
target_include_directories(platform_impl_g3
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(platform_impl_g3
PUBLIC
"platform_types"
"platform_api"
"platform_impl_shared_atomic_boolean"
"platform_impl_shared_posix_condition_variable"
"platform_impl_shared_posix_lock"
"platform_port_string"
"absl::base"
"absl::synchronization"
"absl::time"
)
@@ -0,0 +1,38 @@
#ifndef PLATFORM_IMPL_G3_ATOMIC_REFERENCE_IMPL_H_
#define PLATFORM_IMPL_G3_ATOMIC_REFERENCE_IMPL_H_
#include "platform/api/atomic_reference.h"
#include "platform/ptr.h"
#include "absl/synchronization/mutex.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
// Provide implementation for absl::any.
class AtomicReferenceImpl : public AtomicReference<absl::any> {
public:
explicit AtomicReferenceImpl(absl::any initial_value)
: value_(std::move(initial_value)) {}
~AtomicReferenceImpl() override = default;
absl::any get() override {
absl::MutexLock lock(&mutex_);
return value_;
}
void set(absl::any value) override {
absl::MutexLock lock(&mutex_);
value_ = std::move(value);
}
private:
absl::Mutex mutex_;
absl::any value_;
};
} // namespace platform
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_G3_ATOMIC_REFERENCE_IMPL_H_
+140
View File
@@ -0,0 +1,140 @@
#include "platform/api/platform.h"
#include <atomic>
#include <memory>
#include "platform/api/atomic_boolean.h"
#include "platform/api/atomic_reference.h"
#include "platform/api/ble.h"
#include "platform/api/ble_v2.h"
#include "platform/api/bluetooth_adapter.h"
#include "platform/api/bluetooth_classic.h"
#include "platform/api/condition_variable.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/hash_utils.h"
#include "platform/api/lock.h"
#include "platform/api/scheduled_executor.h"
#include "platform/api/server_sync.h"
#include "platform/api/settable_future.h"
#include "platform/api/submittable_executor.h"
#include "platform/api/system_clock.h"
#include "platform/api/thread_utils.h"
#include "platform/api/webrtc.h"
#include "platform/api/wifi.h"
#include "platform/impl/g3/atomic_reference_impl.h"
#include "platform/impl/g3/settable_future_impl.h"
#include "platform/impl/g3/system_clock_impl.h"
#include "platform/impl/shared/atomic_boolean_impl.h"
#include "platform/impl/shared/posix_condition_variable.h"
#include "platform/impl/shared/posix_lock.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
namespace platform {
Ptr<SubmittableExecutor> ImplementationPlatform::createSingleThreadExecutor() {
return Ptr<SubmittableExecutor>(/*new SingleThreadExecutorImpl()*/);
}
Ptr<SubmittableExecutor> ImplementationPlatform::createMultiThreadExecutor(
int max_concurrency) {
return Ptr<SubmittableExecutor>(/*new MultiThreadExecutorImpl()*/);
}
Ptr<ScheduledExecutor> ImplementationPlatform::createScheduledExecutor() {
return Ptr<ScheduledExecutor>(/*new ScheduledExecutorImpl()*/);
}
Ptr<AtomicReference<absl::any>>
ImplementationPlatform::createAtomicReferenceAny(absl::any initial_value) {
return Ptr<AtomicReference<absl::any>>(
new AtomicReferenceImpl(initial_value));
}
Ptr<SettableFuture<absl::any>>
ImplementationPlatform::createSettableFutureAny() {
return Ptr<SettableFuture<std::any>>(new SettableFutureImpl{});
}
Ptr<BluetoothAdapter> ImplementationPlatform::createBluetoothAdapter() {
return Ptr<BluetoothAdapter>{};
}
Ptr<WifiMedium> ImplementationPlatform::createWifiMedium() {
return Ptr<WifiMedium>();
}
Ptr<CountDownLatch> ImplementationPlatform::createCountDownLatch(
std::int32_t count) {
return Ptr<CountDownLatch>(/*new CountDownLatchImpl(count)*/);
}
Ptr<ThreadUtils> ImplementationPlatform::createThreadUtils() {
return Ptr<ThreadUtils>(/*new ThreadUtilsImpl()*/);
}
Ptr<SystemClock> ImplementationPlatform::createSystemClock() {
return Ptr<SystemClock>(new SystemClockImpl());
}
Ptr<AtomicBoolean> ImplementationPlatform::createAtomicBoolean(
bool initial_value) {
return Ptr<AtomicBoolean>(new AtomicBooleanImpl(initial_value));
}
Ptr<BluetoothClassicMedium>
ImplementationPlatform::createBluetoothClassicMedium() {
return Ptr<BluetoothClassicMedium>();
}
Ptr<BLEMedium> ImplementationPlatform::createBLEMedium() {
return Ptr<BLEMedium>();
}
Ptr<BLEMediumV2> ImplementationPlatform::createBLEMediumV2() {
return Ptr<BLEMediumV2>();
}
Ptr<ServerSyncMedium> ImplementationPlatform::createServerSyncMedium() {
return Ptr<ServerSyncMedium>(/*new ServerSyncMediumImpl()*/);
}
Ptr<WifiLanMedium> ImplementationPlatform::createWifiLanMedium() {
return Ptr<WifiLanMedium>();
}
//Ptr<WebRtcSignalingMessenger>
//ImplementationPlatform::createWebRtcSignalingMessenger(
// const std::string& self_id) {
// return Ptr<WebRtcSignalingMessenger>(/*new FCMSignalingMessenger()*/);
//}
Ptr<Lock> ImplementationPlatform::createLock() {
return Ptr<Lock>(new PosixLock());
}
Ptr<ConditionVariable> ImplementationPlatform::createConditionVariable(
Ptr<Lock> lock) {
return Ptr<ConditionVariable>(new PosixConditionVariable(lock));
}
Ptr<HashUtils> ImplementationPlatform::createHashUtils() {
return Ptr<HashUtils>(/*new HashUtilsImpl()*/);
}
std::string ImplementationPlatform::getDeviceId() {
// TODO(alexchau): Get deviceId from base
return "google3";
}
std::string ImplementationPlatform::getPayloadPath(int64_t payload_id) {
return "/tmp/" + std::to_string(payload_id);
}
} // namespace platform
} // namespace nearby
} // namespace location
@@ -0,0 +1,94 @@
#ifndef PLATFORM_IMPL_G3_SETTABLE_FUTURE_IMPL_H_
#define PLATFORM_IMPL_G3_SETTABLE_FUTURE_IMPL_H_
#include <utility>
#include "platform/api/platform.h"
#include "platform/api/settable_future.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/clock.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
class SettableFutureImpl : public SettableFuture<absl::any> {
public:
explicit SettableFutureImpl() = default;
~SettableFutureImpl() override = default;
bool set(absl::any value) override {
absl::MutexLock lock(&mutex_);
if (!done_) {
value_ = std::move(value);
done_ = true;
exception_ = {Exception::kSuccess};
completed_.SignalAll();
}
return true;
}
bool setException(Exception exception) override {
absl::MutexLock lock(&mutex_);
return SetExceptionLocked(exception);
}
void addListener(Ptr<Runnable> runnable, Executor* executor) override {}
ExceptionOr<std::any> get() override {
absl::MutexLock lock(&mutex_);
while (!done_) {
completed_.Wait(&mutex_);
}
return exception_.value != Exception::kSuccess
? ExceptionOr<std::any>{exception_.value}
: ExceptionOr<std::any>{value_};
}
ExceptionOr<std::any> get(std::int64_t timeout_ms) override {
absl::MutexLock lock(&mutex_);
absl::Duration timeout = absl::Milliseconds(timeout_ms);
while (!done_) {
absl::Time start_time = absl::Now();
if (completed_.WaitWithTimeout(&mutex_, timeout)) {
SetExceptionLocked({Exception::kTimeout});
break;
}
absl::Duration spent = absl::Now() - start_time;
if (spent < timeout) {
timeout -= spent;
} else if (!done_) {
SetExceptionLocked({Exception::kTimeout});
break;
}
}
return exception_.value != Exception::kSuccess
? ExceptionOr<std::any>{exception_.value}
: ExceptionOr<std::any>{value_};
}
private:
bool SetExceptionLocked(Exception exception) {
if (!done_) {
exception_ = exception.value != Exception::kSuccess
? exception
: Exception{Exception::kFailed};
done_ = true;
completed_.SignalAll();
}
return true;
}
absl::Mutex mutex_;
absl::CondVar completed_;
bool done_{false};
absl::any value_;
Exception exception_{Exception::kFailed};
};
} // namespace platform
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_G3_SETTABLE_FUTURE_IMPL_H_
+23
View File
@@ -0,0 +1,23 @@
#ifndef PLATFORM_IMPL_G3_SYSTEM_CLOCK_IMPL_H_
#define PLATFORM_IMPL_G3_SYSTEM_CLOCK_IMPL_H_
#include <cstdint>
#include "platform/api/system_clock.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
namespace location {
namespace nearby {
class SystemClockImpl : public SystemClock {
public:
std::int64_t elapsedRealtime() override {
return absl::ToUnixMillis(absl::Now());
}
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_G3_SYSTEM_CLOCK_IMPL_H_
+6 -4
View File
@@ -1,10 +1,10 @@
cc_library(
name = "sample",
name = "sample_platform",
srcs = [
"sample_wifi_medium.cc",
"sample_wifi_medium.h",
"atomic_reference_impl.h",
"sample_platform.cc",
"settable_future_impl.h",
],
hdrs = ["sample_platform.h"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core:__subpackages__",
@@ -14,7 +14,9 @@ cc_library(
"//platform:types",
"//platform:utils",
"//platform/api",
"//platform/impl/shared/sample:sample_wifi_medium",
"//platform/port:string",
"//absl/time",
"//absl/types:any",
],
)
@@ -0,0 +1,25 @@
#ifndef PLATFORM_IMPL_SAMPLE_ATOMIC_REFERENCE_IMPL_H_
#define PLATFORM_IMPL_SAMPLE_ATOMIC_REFERENCE_IMPL_H_
#include "platform/api/atomic_reference_def.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
// Provide implementation for absl::any.
class AtomicReferenceImpl : public AtomicReference<absl::any> {
public:
explicit AtomicReferenceImpl(absl::any initial_value) {}
~AtomicReferenceImpl() override = default;
absl::any get() override { return {}; }
void set(absl::any value) override {}
};
} // namespace platform
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SAMPLE_ATOMIC_REFERENCE_IMPL_H_
+125
View File
@@ -0,0 +1,125 @@
#include <cstdint>
#include "platform/api/atomic_boolean.h"
#include "platform/api/atomic_reference_def.h"
#include "platform/api/ble.h"
#include "platform/api/ble_v2.h"
#include "platform/api/bluetooth_adapter.h"
#include "platform/api/bluetooth_classic.h"
#include "platform/api/condition_variable.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/hash_utils.h"
#include "platform/api/lock.h"
#include "platform/api/platform.h"
#include "platform/api/server_sync.h"
#include "platform/api/settable_future_def.h"
#include "platform/api/submittable_executor_def.h"
#include "platform/api/system_clock.h"
#include "platform/api/thread_utils.h"
#include "platform/api/wifi.h"
#include "platform/cancelable.h"
#include "platform/impl/sample/atomic_reference_impl.h"
#include "platform/impl/sample/settable_future_impl.h"
#include "platform/impl/shared/sample/sample_wifi_medium.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
Ptr<ScheduledExecutor> ImplementationPlatform::createScheduledExecutor() {
return Ptr<ScheduledExecutor>{};
}
Ptr<SubmittableExecutor> ImplementationPlatform::createSingleThreadExecutor() {
return Ptr<SubmittableExecutor>{};
}
Ptr<SubmittableExecutor> ImplementationPlatform::createMultiThreadExecutor(
int max_concurrency) {
return Ptr<SubmittableExecutor>{};
}
Ptr<AtomicReference<absl::any>>
ImplementationPlatform::createAtomicReferenceAny(absl::any initial_value) {
return Ptr<AtomicReference<absl::any>>(
new AtomicReferenceImpl(initial_value));
}
Ptr<SettableFuture<absl::any>>
ImplementationPlatform::createSettableFutureAny() {
return Ptr<SettableFuture<absl::any>>(new SettableFutureImpl{});
}
Ptr<BluetoothAdapter> ImplementationPlatform::createBluetoothAdapter() {
return Ptr<BluetoothAdapter>{};
}
Ptr<WifiMedium> ImplementationPlatform::createWifiMedium() {
return Ptr<WifiMedium>();
}
Ptr<CountDownLatch> ImplementationPlatform::createCountDownLatch(
std::int32_t count) {
return Ptr<CountDownLatch>{};
}
Ptr<ThreadUtils> ImplementationPlatform::createThreadUtils() {
return Ptr<ThreadUtils>{};
}
Ptr<SystemClock> ImplementationPlatform::createSystemClock() {
return Ptr<SystemClock>{};
}
Ptr<AtomicBoolean> ImplementationPlatform::createAtomicBoolean(
bool initial_value) {
return Ptr<AtomicBoolean>{};
}
Ptr<BluetoothClassicMedium>
ImplementationPlatform::createBluetoothClassicMedium() {
return Ptr<BluetoothClassicMedium>();
}
Ptr<BLEMedium> ImplementationPlatform::createBLEMedium() {
return Ptr<BLEMedium>();
}
Ptr<BLEMediumV2> ImplementationPlatform::createBLEMediumV2() {
return Ptr<BLEMediumV2>();
}
Ptr<ServerSyncMedium> ImplementationPlatform::createServerSyncMedium() {
return Ptr<ServerSyncMedium>{};
}
Ptr<WebRtcSignalingMessenger>
ImplementationPlatform::createWebRtcSignalingMessenger(
const std::string& self_id) {
return Ptr<WebRtcSignalingMessenger>{};
}
Ptr<Lock> ImplementationPlatform::createLock() { return Ptr<Lock>{}; }
Ptr<ConditionVariable> ImplementationPlatform::createConditionVariable(
Ptr<Lock> lock) {
return Ptr<ConditionVariable>{};
}
Ptr<HashUtils> ImplementationPlatform::createHashUtils() {
return Ptr<HashUtils>{};
}
std::string ImplementationPlatform::getDeviceId() { return "sample"; }
std::string ImplementationPlatform::getPayloadPath(int64_t payload_id) {
return "/tmp/sample-" + std::to_string(payload_id);
}
} // namespace platform
} // namespace nearby
} // namespace location
-141
View File
@@ -1,141 +0,0 @@
#ifndef PLATFORM_IMPL_SAMPLE_SAMPLE_PLATFORM_H_
#define PLATFORM_IMPL_SAMPLE_SAMPLE_PLATFORM_H_
#include <cstdint>
#include "platform/api/atomic_boolean.h"
#include "platform/api/atomic_reference.h"
#include "platform/api/ble.h"
#include "platform/api/ble_v2.h"
#include "platform/api/bluetooth_adapter.h"
#include "platform/api/bluetooth_classic.h"
#include "platform/api/condition_variable.h"
#include "platform/api/count_down_latch.h"
#include "platform/api/hash_utils.h"
#include "platform/api/lock.h"
#include "platform/api/multi_thread_executor.h"
#include "platform/api/settable_future.h"
#include "platform/api/single_thread_executor.h"
#include "platform/api/system_clock.h"
#include "platform/api/thread_utils.h"
#include "platform/api/wifi.h"
#include "platform/cancelable.h"
#include "platform/impl/sample/sample_wifi_medium.h"
#include "platform/port/string.h"
#include "platform/ptr.h"
#include "platform/runnable.h"
namespace location {
namespace nearby {
namespace sample {
// The SamplePlatform class below shows an example of the factory functions
// and typedefs.
class SamplePlatform {
public:
class SampleSubmittableExecutor
: public SubmittableExecutor<SampleSubmittableExecutor> {
public:
template <typename T>
Ptr<Future<T> > submit(Ptr<Callable<T> > callable) {
return Ptr<Future<T> >();
}
};
class SampleSingleThreadExecutor
: public SingleThreadExecutor<SampleSubmittableExecutor> {
public:
void execute(Ptr<Runnable> runnable) override {}
void shutdown() override {}
};
class SampleMultiThreadExecutor
: public MultiThreadExecutor<SampleSubmittableExecutor> {
public:
void execute(Ptr<Runnable> runnable) override {}
void shutdown() override {}
};
class SampleScheduledExecutor {
public:
Ptr<Cancelable> schedule(Ptr<Runnable> runnable,
std::int64_t delay_millis) {
return Ptr<Cancelable>();
}
void shutdown() {}
};
typedef SampleSingleThreadExecutor SingleThreadExecutorType;
static Ptr<SingleThreadExecutorType> createSingleThreadExecutor() {
return MakePtr(new SingleThreadExecutorType());
}
typedef SampleMultiThreadExecutor MultiThreadExecutorType;
static Ptr<MultiThreadExecutorType> createMultiThreadExecutor(
std::int32_t max_concurrency) {
return MakePtr(new MultiThreadExecutorType());
}
typedef SampleScheduledExecutor ScheduledExecutorType;
static Ptr<ScheduledExecutorType> createScheduledExecutor() {
return MakePtr(new ScheduledExecutorType());
}
static Ptr<BluetoothAdapter> createBluetoothAdapter() {
return Ptr<BluetoothAdapter>();
}
static Ptr<WifiMedium> createWifiMedium() {
return MakePtr(new SampleWifiMedium());
}
static Ptr<CountDownLatch> createCountDownLatch(std::int32_t count) {
return Ptr<CountDownLatch>();
}
template <typename T>
static Ptr<SettableFuture<T> > createSettableFuture() {
return Ptr<SettableFuture<T> >();
}
static Ptr<ThreadUtils> createThreadUtils() { return Ptr<ThreadUtils>(); }
static Ptr<SystemClock> createSystemClock() { return Ptr<SystemClock>(); }
static Ptr<AtomicBoolean> createAtomicBoolean(bool initial_value) {
return Ptr<AtomicBoolean>();
}
template <typename T>
static Ptr<AtomicReference<T> > createAtomicReference(T initial_value) {
return Ptr<AtomicReference<T> >();
}
static Ptr<BluetoothClassicMedium> createBluetoothClassicMedium() {
return Ptr<BluetoothClassicMedium>();
}
static Ptr<BLEMedium> createBLEMedium() { return Ptr<BLEMedium>(); }
static Ptr<BLEMediumV2> createBLEMediumV2() { return Ptr<BLEMediumV2>(); }
static Ptr<Lock> createLock() { return Ptr<Lock>(); }
static Ptr<ConditionVariable> createConditionVariable(Ptr<Lock> lock) {
return Ptr<ConditionVariable>();
}
static Ptr<HashUtils> createHashUtils() { return Ptr<HashUtils>(); }
static std::string getDeviceId() { return ""; }
static std::string getPayloadPath(int64_t payload_id) {
return "/tmp/" + std::to_string(payload_id);
}
};
} // namespace sample
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SAMPLE_SAMPLE_PLATFORM_H_
@@ -0,0 +1,35 @@
#ifndef PLATFORM_IMPL_SAMPLE_SETTABLE_FUTURE_IMPL_H_
#define PLATFORM_IMPL_SAMPLE_SETTABLE_FUTURE_IMPL_H_
#include "platform/api/settable_future_def.h"
#include "absl/types/any.h"
namespace location {
namespace nearby {
namespace platform {
class SettableFutureImpl : public SettableFuture<absl::any> {
public:
explicit SettableFutureImpl() = default;
~SettableFutureImpl() override = default;
bool set(absl::any value) override { return true; }
bool setException(Exception exception) override { return true; }
void addListener(Ptr<Runnable> runnable, Executor* executor) override {}
ExceptionOr<std::any> get() override {
return ExceptionOr<std::any>{Exception{Exception::kFailed}};
}
ExceptionOr<std::any> get(std::int64_t timeout_ms) override {
return ExceptionOr<std::any>{Exception{Exception::kFailed}};
}
};
} // namespace platform
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SAMPLE_SETTABLE_FUTURE_IMPL_H_
+45
View File
@@ -0,0 +1,45 @@
cc_library(
name = "posix_lock",
srcs = [
"posix_lock.cc",
],
hdrs = [
"posix_lock.h",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//platform/impl:__subpackages__",
],
deps = [
"//platform/api",
],
)
cc_library(
name = "posix_condition_variable",
srcs = [
"posix_condition_variable.cc",
],
hdrs = [
"posix_condition_variable.h",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//platform/impl:__subpackages__",
],
deps = [
":posix_lock",
"//platform:types",
"//platform/api:condition_variable",
],
)
cc_library(
name = "atomic_boolean",
hdrs = ["atomic_boolean_impl.h"],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//platform/impl:__subpackages__",
],
deps = ["//platform/api"],
)
+67
View File
@@ -0,0 +1,67 @@
add_library(platform_impl_shared_posix_lock STATIC)
target_sources(platform_impl_shared_posix_lock
PRIVATE
"posix_lock.cc"
PUBLIC
"posix_lock.h"
)
target_include_directories(platform_impl_shared_posix_lock
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(platform_impl_shared_posix_lock
PUBLIC
platform_api
platform_types
)
add_library(platform_impl_shared_posix_condition_variable STATIC)
target_sources(platform_impl_shared_posix_condition_variable
PRIVATE
"posix_condition_variable.cc"
PUBLIC
"posix_condition_variable.h"
)
target_include_directories(platform_impl_shared_posix_condition_variable
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(platform_impl_shared_posix_condition_variable
PUBLIC
platform_api
platform_impl_shared_posix_lock
platform_types
absl::raw_logging_internal
)
add_library(platform_impl_shared_atomic_boolean STATIC)
target_sources(platform_impl_shared_atomic_boolean
PUBLIC
"atomic_boolean_impl.h"
)
target_include_directories(platform_impl_shared_atomic_boolean
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_link_libraries(platform_impl_shared_atomic_boolean
PUBLIC
platform_api
platform_types
)
set_target_properties(platform_impl_shared_atomic_boolean
PROPERTIES
LINKER_LANGUAGE CXX
)
add_subdirectory(sample)
@@ -0,0 +1,33 @@
#ifndef PLATFORM_IMPL_SHARED_ATOMIC_BOOLEAN_IMPL_H_
#define PLATFORM_IMPL_SHARED_ATOMIC_BOOLEAN_IMPL_H_
#include <atomic>
#include "platform/api/atomic_boolean.h"
namespace location {
namespace nearby {
class AtomicBooleanImpl : public AtomicBoolean {
public:
explicit AtomicBooleanImpl(bool initial_value) : value_(initial_value) {}
~AtomicBooleanImpl() override = default;
// AtomicBoolean:
bool get() override {
return value_.load();
}
// AtomicBoolean:
void set(bool value) override {
value_.store(value);
}
private:
std::atomic_bool value_;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SHARED_ATOMIC_BOOLEAN_IMPL_H_
@@ -0,0 +1,28 @@
#include "platform/impl/shared/posix_condition_variable.h"
namespace location {
namespace nearby {
PosixConditionVariable::PosixConditionVariable(Ptr<PosixLock> lock)
: lock_(lock), attr_(), cond_() {
pthread_condattr_init(&attr_);
pthread_cond_init(&cond_, &attr_);
}
PosixConditionVariable::~PosixConditionVariable() {
pthread_cond_destroy(&cond_);
pthread_condattr_destroy(&attr_);
}
void PosixConditionVariable::notify() { pthread_cond_broadcast(&cond_); }
Exception::Value PosixConditionVariable::wait() {
pthread_cond_wait(&cond_, &(lock_->mutex_));
return Exception::kSuccess;
}
} // namespace nearby
} // namespace location
@@ -0,0 +1,30 @@
#ifndef PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
#define PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
#include <pthread.h>
#include "platform/api/condition_variable.h"
#include "platform/impl/shared/posix_lock.h"
#include "platform/ptr.h"
namespace location {
namespace nearby {
class PosixConditionVariable : public ConditionVariable {
public:
explicit PosixConditionVariable(Ptr<PosixLock> lock);
~PosixConditionVariable() override;
void notify() override;
Exception::Value wait() override;
private:
Ptr<PosixLock> lock_;
pthread_condattr_t attr_;
pthread_cond_t cond_;
};
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SHARED_POSIX_CONDITION_VARIABLE_H_
@@ -1,24 +1,24 @@
#include "platform/impl/default/default_lock.h"
#include "platform/impl/shared/posix_lock.h"
namespace location {
namespace nearby {
DefaultLock::DefaultLock() : attr_(), mutex_() {
PosixLock::PosixLock() : attr_(), mutex_() {
pthread_mutexattr_init(&attr_);
pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex_, &attr_);
}
DefaultLock::~DefaultLock() {
PosixLock::~PosixLock() {
pthread_mutex_destroy(&mutex_);
pthread_mutexattr_destroy(&attr_);
}
void DefaultLock::lock() { pthread_mutex_lock(&mutex_); }
void PosixLock::lock() { pthread_mutex_lock(&mutex_); }
void DefaultLock::unlock() { pthread_mutex_unlock(&mutex_); }
void PosixLock::unlock() { pthread_mutex_unlock(&mutex_); }
} // namespace nearby
} // namespace location
@@ -1,5 +1,5 @@
#ifndef PLATFORM_IMPL_DEFAULT_DEFAULT_LOCK_H_
#define PLATFORM_IMPL_DEFAULT_DEFAULT_LOCK_H_
#ifndef PLATFORM_IMPL_SHARED_POSIX_LOCK_H_
#define PLATFORM_IMPL_SHARED_POSIX_LOCK_H_
#include <pthread.h>
@@ -8,16 +8,16 @@
namespace location {
namespace nearby {
class DefaultLock : public Lock {
class PosixLock : public Lock {
public:
DefaultLock();
~DefaultLock() override;
PosixLock();
~PosixLock() override;
void lock() override;
void unlock() override;
private:
friend class DefaultConditionVariable;
friend class PosixConditionVariable;
pthread_mutexattr_t attr_;
pthread_mutex_t mutex_;
@@ -26,4 +26,4 @@ class DefaultLock : public Lock {
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_DEFAULT_DEFAULT_LOCK_H_
#endif // PLATFORM_IMPL_SHARED_POSIX_LOCK_H_
+22
View File
@@ -0,0 +1,22 @@
cc_library(
name = "sample_wifi_medium",
srcs = [
"sample_wifi_medium.cc",
],
hdrs = [
"sample_wifi_medium.h",
],
visibility = [
"//googlemac/iPhone/Shared/Nearby/Connections:__subpackages__",
"//core:__subpackages__",
"//platform/impl:__subpackages__",
"//location/nearby/setup/core:__subpackages__",
],
deps = [
"//platform:types",
"//platform:utils",
"//platform/api",
"//platform/port:string",
"//absl/time",
],
)
@@ -0,0 +1,17 @@
add_library(platform_impl_shared_sample STATIC)
target_sources(platform_impl_shared_sample
PRIVATE
sample_wifi_medium.cc
PUBLIC
sample_wifi_medium.h
)
target_link_libraries(platform_impl_shared_sample
PUBLIC
absl::time
platform_api
platform_port_string
platform_types
platform_utils
)
@@ -1,4 +1,4 @@
#include "platform/impl/sample/sample_wifi_medium.h"
#include "platform/impl/shared/sample/sample_wifi_medium.h"
#include <cstdint>
@@ -1,5 +1,5 @@
#ifndef PLATFORM_IMPL_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
#define PLATFORM_IMPL_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
#ifndef PLATFORM_IMPL_SHARED_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
#define PLATFORM_IMPL_SHARED_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
#include "platform/api/wifi.h"
@@ -56,4 +56,4 @@ class SampleWifiMedium : public WifiMedium {
} // namespace nearby
} // namespace location
#endif // PLATFORM_IMPL_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
#endif // PLATFORM_IMPL_SHARED_SAMPLE_SAMPLE_WIFI_MEDIUM_H_
+24 -35
View File
@@ -1,19 +1,21 @@
#include "platform/pipe.h"
#include "platform/api/platform.h"
#include "platform/synchronized.h"
namespace location {
namespace nearby {
namespace {
using Platform = platform::ImplementationPlatform;
}
namespace pipe {
template <typename Platform>
class PipeInputStream : public InputStream {
public:
explicit PipeInputStream(Ptr<Pipe<Platform>> pipe) : pipe_(pipe) {}
~PipeInputStream() override {
close();
}
explicit PipeInputStream(Ptr<Pipe> pipe) : pipe_(pipe) {}
~PipeInputStream() override { close(); }
ExceptionOr<ConstPtr<ByteArray>> read() override { return read(kChunkSize); }
ExceptionOr<ConstPtr<ByteArray>> read(std::int64_t size) override {
@@ -27,18 +29,15 @@ class PipeInputStream : public InputStream {
}
private:
static const std::int64_t kChunkSize = 64 * 1024;
static constexpr std::int64_t kChunkSize = 64 * 1024;
Ptr<Pipe<Platform>> pipe_;
Ptr<Pipe> pipe_;
};
template <typename Platform>
class PipeOutputStream : public OutputStream {
public:
explicit PipeOutputStream(Ptr<Pipe<Platform>> pipe) : pipe_(pipe) {}
~PipeOutputStream() override {
close();
}
explicit PipeOutputStream(Ptr<Pipe> pipe) : pipe_(pipe) {}
~PipeOutputStream() override { close(); }
Exception::Value write(ConstPtr<ByteArray> data) override {
// Avoid leaks.
@@ -59,13 +58,12 @@ class PipeOutputStream : public OutputStream {
}
private:
Ptr<Pipe<Platform>> pipe_;
Ptr<Pipe> pipe_;
};
} // namespace pipe
template <typename Platform>
Pipe<Platform>::Pipe()
Pipe::Pipe()
: lock_(Platform::createLock()),
cond_(Platform::createConditionVariable(lock_.get())),
buffer_(),
@@ -73,8 +71,7 @@ Pipe<Platform>::Pipe()
output_stream_closed_(false),
read_all_chunks_(false) {}
template <typename Platform>
Pipe<Platform>::~Pipe() {
Pipe::~Pipe() {
// Deallocate all the chunks still left in buffer_.
for (BufferType::iterator chunk_iter = buffer_.begin();
chunk_iter != buffer_.end(); ++chunk_iter) {
@@ -82,20 +79,17 @@ Pipe<Platform>::~Pipe() {
}
}
template <typename Platform>
Ptr<InputStream> Pipe<Platform>::createInputStream(Ptr<Pipe> self) {
Ptr<InputStream> Pipe::createInputStream(Ptr<Pipe> self) {
assert(self.isRefCounted());
return MakeRefCountedPtr(new pipe::PipeInputStream<Platform>(self));
return MakeRefCountedPtr(new pipe::PipeInputStream(self));
}
template <typename Platform>
Ptr<OutputStream> Pipe<Platform>::createOutputStream(Ptr<Pipe> self) {
Ptr<OutputStream> Pipe::createOutputStream(Ptr<Pipe> self) {
assert(self.isRefCounted());
return MakeRefCountedPtr(new pipe::PipeOutputStream<Platform>(self));
return MakeRefCountedPtr(new pipe::PipeOutputStream(self));
}
template <typename Platform>
ExceptionOr<ConstPtr<ByteArray>> Pipe<Platform>::read(std::int64_t size) {
ExceptionOr<ConstPtr<ByteArray>> Pipe::read(std::int64_t size) {
Synchronized s(lock_.get());
// We're done reading all the chunks that were written before the OutputStream
@@ -148,15 +142,13 @@ ExceptionOr<ConstPtr<ByteArray>> Pipe<Platform>::read(std::int64_t size) {
}
}
template <typename Platform>
Exception::Value Pipe<Platform>::write(ConstPtr<ByteArray> data) {
Exception::Value Pipe::write(ConstPtr<ByteArray> data) {
Synchronized s(lock_.get());
return writeLocked(data);
}
template <typename Platform>
void Pipe<Platform>::markInputStreamClosed() {
void Pipe::markInputStreamClosed() {
Synchronized s(lock_.get());
input_stream_closed_ = true;
@@ -165,8 +157,7 @@ void Pipe<Platform>::markInputStreamClosed() {
cond_->notify();
}
template <typename Platform>
void Pipe<Platform>::markOutputStreamClosed() {
void Pipe::markOutputStreamClosed() {
Synchronized s(lock_.get());
// Write a sentinel null chunk before marking output_stream_closed as true.
@@ -174,8 +165,7 @@ void Pipe<Platform>::markOutputStreamClosed() {
output_stream_closed_ = true;
}
template <typename Platform>
Exception::Value Pipe<Platform>::writeLocked(ConstPtr<ByteArray> data) {
Exception::Value Pipe::writeLocked(ConstPtr<ByteArray> data) {
// Avoid leaks.
ScopedPtr<ConstPtr<ByteArray>> scoped_data(data);
@@ -190,8 +180,7 @@ Exception::Value Pipe<Platform>::writeLocked(ConstPtr<ByteArray> data) {
return Exception::NONE;
}
template <typename Platform>
bool Pipe<Platform>::eitherStreamClosed() const {
bool Pipe::eitherStreamClosed() const {
return input_stream_closed_ || output_stream_closed_;
}
-7
View File
@@ -17,14 +17,11 @@ namespace nearby {
namespace pipe {
template <typename>
class PipeInputStream;
template <typename>
class PipeOutputStream;
} // namespace pipe
template <typename Platform>
class Pipe {
public:
Pipe();
@@ -42,9 +39,7 @@ class Pipe {
// classes.
//////////////////////////////////////////////////////////////////////////////
template <typename>
friend class pipe::PipeInputStream;
template <typename>
friend class pipe::PipeOutputStream;
ExceptionOr<ConstPtr<ByteArray> > read(std::int64_t size);
@@ -70,6 +65,4 @@ class Pipe {
} // namespace nearby
} // namespace location
#include "platform/pipe.cc"
#endif // PLATFORM_PIPE_H_
+2 -12
View File
@@ -4,8 +4,7 @@
#include <cstring>
#include "platform/impl/default/default_condition_variable.h"
#include "platform/impl/default/default_lock.h"
#include "platform/api/platform.h"
#include "platform/port/string.h"
#include "platform/prng.h"
#include "platform/ptr.h"
@@ -17,16 +16,7 @@ namespace location {
namespace nearby {
namespace {
class SamplePlatform {
public:
static Ptr<Lock> createLock() { return MakePtr(new DefaultLock()); }
static Ptr<ConditionVariable> createConditionVariable(Ptr<Lock> lock) {
return MakePtr(
new DefaultConditionVariable(DowncastPtr<DefaultLock>(lock)));
}
};
using SamplePipe = Pipe<SamplePlatform>;
using SamplePipe = Pipe;
TEST(PipeTest, SimpleWriteRead) {
auto pipe = MakeRefCountedPtr(new SamplePipe());
+18 -9
View File
@@ -46,6 +46,7 @@ class Ptr {
Ptr() = default;
explicit Ptr(T* pointee) : ptr_(pointee) {}
Ptr(const Ptr& that) = default;
Ptr(Ptr&& that) = default;
Ptr(std::shared_ptr<T> ptr) : ptr_(ptr) {} // NOLINT
@@ -81,18 +82,23 @@ class Ptr {
return *(this->ptr_) < *(other.ptr_);
}
// No-op: refcounted objects will be destroyed correctly
ABSL_DEPRECATED("Use c++ smart pointers directly instead of Ptr<T>")
void destroy(bool = true) {}
void destroy(bool = true) {
// Legacy code expects isNull() to return true after destroy().
ptr_.reset();
}
// No-op: refcounted objects will be destroyed correctly
ABSL_DEPRECATED("Use c++ smart pointers directly instead of Ptr<T>")
void clear() {}
void clear() {
// Legacy code expects isNull() to return true after clear().
ptr_.reset();
}
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_.get(); }
T* get() { return ptr_.get(); }
T* get() const { return ptr_.get(); }
void reset() { return ptr_.reset(); }
ABSL_DEPRECATED("Use c++ smart pointers directly instead of Ptr<T>")
@@ -180,11 +186,12 @@ class ScopedPtr {
// Accessor for the underlying Ptr.
PtrType get() const { return this->ptr_; }
// Does nothing;
// this is to avoid unintended destruction of a managed pointer.
// TODO(b/149938110): remove this completely.
PtrType release() {
return ptr_;
// Legacy code expects isNull() to return true after release().
PtrType ptr = std::move(ptr_);
ptr_.clear();
return ptr;
}
private:
@@ -252,14 +259,16 @@ ConstPtr<T> ConstifyPtr(Ptr<T> ptr) {
// Ptr<MyChild> my_child_ptr = DowncastPtr<MyChild>(my_base_ptr);
template <typename ChildT, typename BaseT>
Ptr<ChildT> DowncastPtr(Ptr<BaseT> base_ptr) {
static_assert(std::is_base_of_v<BaseT, ChildT>);
static_assert(std::is_base_of<BaseT, ChildT>::value,
"Types do not share base class.");
return Ptr<ChildT>(std::static_pointer_cast<ChildT>(base_ptr.ptr_));
}
// ConstPtr counterpart to DowncastPtr().
template <typename ChildT, typename BaseT>
ConstPtr<ChildT> DowncastConstPtr(ConstPtr<BaseT> base_ptr) {
static_assert(std::is_base_of_v<BaseT, ChildT>);
static_assert(std::is_base_of<BaseT, ChildT>::value,
"Types do not share base class.");
return ConstPtr<ChildT>(
std::static_pointer_cast<const ChildT>(base_ptr.ptr_));
}
+3 -2
View File
@@ -116,7 +116,8 @@ TEST(PtrTest, ScopedPtr_Release_RefCounted) {
Ptr<int> ref_counted_2 = scoped_ref_counted_1.release();
ASSERT_EQ(*scoped_ref_counted_1, *ref_counted_2);
ASSERT_TRUE(scoped_ref_counted_1.isNull());
ASSERT_EQ(1234, *ref_counted_1);
ASSERT_EQ(1234, *ref_counted_2);
}
@@ -127,7 +128,7 @@ TEST(PtrTest, ScopedPtr_Release_RefCounted_Stay_Valid) {
Ptr<int> ref_counted_3 = scoped_ref_counted_1.release();
ASSERT_EQ(*scoped_ref_counted_1, *ref_counted_3);
ASSERT_TRUE(scoped_ref_counted_1.isNull());
ASSERT_EQ(1234, *ref_counted_2);
ASSERT_EQ(1234, *ref_counted_3);
}
+84
View File
@@ -0,0 +1,84 @@
#include "platform/api/settable_future.h"
#include "platform/api/platform.h"
#include "platform/ptr.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace location {
namespace nearby {
namespace {
enum TestEnum {
kValue1 = 1,
kValue2 = 2,
};
enum class ScopedTestEnum {
kValue1 = 1,
kValue2 = 2,
};
struct BigSizedStruct {
int data[100]{};
};
bool operator==(const BigSizedStruct& a, const BigSizedStruct& b) {
return memcmp(a.data, b.data, sizeof(BigSizedStruct::data)) == 0;
}
bool operator!=(const BigSizedStruct& a, const BigSizedStruct& b) {
return !(a == b);
}
} // namespace
TEST(SettableFutureTest, SupportIntegralTypes) {
auto p = platform::ImplementationPlatform::createSettableFuture<int>();
p->set(5);
ASSERT_EQ(p->get().exception(), Exception::kSuccess);
ASSERT_EQ(p->get().result(), 5);
}
TEST(SettableFutureTest, SetExceptionIsPropagated) {
auto p = platform::ImplementationPlatform::createSettableFuture<int>();
p->setException({Exception::kIo});
ASSERT_EQ(p->get().exception(), Exception::kIo);
}
TEST(SettableFutureTest, SupportEnum) {
auto p = platform::ImplementationPlatform::createSettableFuture<TestEnum>();
p->set(TestEnum::kValue1);
ASSERT_EQ(p->get().exception(), Exception::kSuccess);
ASSERT_EQ(p->get().result(), TestEnum::kValue1);
}
TEST(SettableFutureTest, SupportScopedEnum) {
auto p =
platform::ImplementationPlatform::createSettableFuture<ScopedTestEnum>();
p->set(ScopedTestEnum::kValue1);
ASSERT_EQ(p->get().exception(), Exception::kSuccess);
ASSERT_EQ(p->get().result(), ScopedTestEnum::kValue1);
}
TEST(SettableFutureTest, SetTakesCopyOfValue) {
// Default constructor is zero-initalizing all data in BigSizedStruct.
BigSizedStruct v1;
auto p = platform::ImplementationPlatform::createSettableFuture<
BigSizedStruct>();
v1.data[0] = 5; // Changing value before calling set() will affect stored
v1.data[7] = 3; // value.
p->set(v1);
v1.data[1] = 6; // Changing value after calling set() will not affect stored
v1.data[5] = 4; // value.
ASSERT_EQ(p->get().exception(), Exception::kSuccess);
BigSizedStruct v2 = p->get().result();
ASSERT_NE(v1, v2);
v1.data[1] = 0;
v1.data[5] = 0;
ASSERT_EQ(v2, v1);
}
} // namespace nearby
} // namespace location