From fbf66ad7e3f845ddbf74b0628ef7789f7944305e Mon Sep 17 00:00:00 2001 From: Francis Tsui Date: Fri, 9 Jan 2026 09:35:22 -0800 Subject: [PATCH] Switch OutputStream::Write to use string_view. PiperOrigin-RevId: 854225267 --- connections/implementation/BUILD | 3 + .../implementation/base_endpoint_channel.cc | 5 +- connections/implementation/internal_payload.h | 13 ++--- .../internal_payload_factory.cc | 15 ++--- .../internal_payload_factory_test.cc | 8 ++- connections/implementation/mediums/BUILD | 1 + connections/implementation/mediums/ble/BUILD | 1 + .../implementation/mediums/ble/ble_socket.cc | 10 ++-- .../implementation/mediums/ble/ble_socket.h | 5 +- .../mediums/ble/ble_socket_test.cc | 8 +-- .../implementation/mediums/ble/bloom_filter.h | 5 ++ .../mediums/multiplex/multiplex_frames.cc | 5 +- .../mediums/multiplex/multiplex_frames.h | 3 +- .../multiplex/multiplex_frames_test.cc | 2 +- .../multiplex/multiplex_output_stream.cc | 7 +-- .../multiplex/multiplex_output_stream.h | 3 +- .../multiplex/multiplex_output_stream_test.cc | 6 +- .../multiplex/multiplex_socket_test.cc | 22 +++---- .../implementation/mediums/webrtc/BUILD | 2 + .../mediums/webrtc/webrtc_socket_impl.cc | 7 ++- .../mediums/webrtc/webrtc_socket_impl.h | 3 +- .../mediums/webrtc/webrtc_socket_impl_test.cc | 11 ++-- .../mediums/webrtc_socket_stub.h | 2 +- connections/implementation/payload_manager.cc | 2 +- .../implementation/payload_manager_test.cc | 58 +++++++++---------- connections/payload_test.cc | 15 +++-- internal/platform/BUILD | 2 + internal/platform/base64_utils.cc | 25 ++++---- internal/platform/byte_array.h | 7 ++- internal/platform/file.cc | 5 +- internal/platform/file.h | 5 +- internal/platform/file_test.cc | 18 +++--- .../apple/Tests/ble_socket_test.mm | 2 +- internal/platform/implementation/apple/awdl.h | 2 +- .../platform/implementation/apple/awdl.mm | 2 +- .../implementation/apple/ble_l2cap_socket.h | 2 +- .../implementation/apple/ble_l2cap_socket.mm | 2 +- .../implementation/apple/ble_medium.mm | 2 +- .../implementation/apple/ble_socket.h | 2 +- .../implementation/apple/ble_socket.mm | 4 +- .../implementation/apple/wifi_hotspot.h | 2 +- .../implementation/apple/wifi_hotspot.mm | 2 +- .../platform/implementation/apple/wifi_lan.h | 3 +- .../platform/implementation/apple/wifi_lan.mm | 2 +- .../platform/implementation/shared/file.cc | 2 +- .../platform/implementation/shared/file.h | 2 +- .../implementation/shared/file_test.cc | 10 ++-- .../implementation/windows/ble_socket.cc | 16 +---- .../implementation/windows/ble_socket.h | 3 +- .../windows/bluetooth_classic_socket.cc | 4 +- .../windows/bluetooth_classic_socket.h | 3 +- .../platform/implementation/windows/file.cc | 2 +- .../platform/implementation/windows/file.h | 2 +- .../implementation/windows/file_test.cc | 6 +- .../windows/nearby_client_socket.cc | 3 +- .../windows/nearby_client_socket.h | 5 +- .../windows/nearby_client_socket_test.cc | 2 +- internal/platform/mock_output_stream.h | 4 +- internal/platform/output_stream.h | 7 ++- internal/platform/pipe.cc | 5 +- internal/platform/pipe_test.cc | 38 ++++++------ 61 files changed, 227 insertions(+), 198 deletions(-) diff --git a/connections/implementation/BUILD b/connections/implementation/BUILD index d5b6f768..30d3fd8f 100644 --- a/connections/implementation/BUILD +++ b/connections/implementation/BUILD @@ -504,6 +504,7 @@ cc_test( "//internal/platform:logging", "//internal/platform:test_util", "//internal/platform:types", + "//internal/platform/implementation:types", "//internal/platform/implementation/g3", # build_cleaner: keep "@com_github_protobuf_matchers//protobuf-matchers", "@com_google_absl//absl/strings", @@ -531,6 +532,7 @@ cc_test( "//internal/platform:logging", "//internal/platform:test_util", "//internal/platform:types", + "//internal/platform/implementation:types", "//internal/platform/implementation/g3", # build_cleaner: keep "//proto:connections_enums_cc_proto", "@com_github_protobuf_matchers//protobuf-matchers", @@ -574,6 +576,7 @@ cc_test( "//internal/platform:types", "//internal/platform/implementation/g3", # build_cleaner: keep "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_absl//absl/strings:string_view", "@com_google_googletest//:gtest_main", ], ) diff --git a/connections/implementation/base_endpoint_channel.cc b/connections/implementation/base_endpoint_channel.cc index f4a5578c..1128cc19 100644 --- a/connections/implementation/base_endpoint_channel.cc +++ b/connections/implementation/base_endpoint_channel.cc @@ -32,7 +32,6 @@ #include "internal/flags/nearby_flags.h" #include "internal/platform/base64_utils.h" #include "internal/platform/byte_array.h" -#include "internal/platform/byte_utils.h" #include "internal/platform/exception.h" #include "internal/platform/implementation/system_clock.h" #include "internal/platform/input_stream.h" @@ -52,7 +51,7 @@ using DisconnectionReason = ::location::nearby::proto::connections::DisconnectionReason; Exception WriteInt(OutputStream* writer, std::int32_t value) { - return writer->Write(byte_utils::IntToBytes(value)); + return Base64Utils::WriteInt(writer, value); } } // namespace @@ -252,7 +251,7 @@ Exception BaseEndpointChannel::Write(const ByteArray& data, << ": Failed to write header: " << write_exception.value; return write_exception; } - write_exception = writer_->Write(*data_to_write); + write_exception = writer_->Write(data_to_write->AsStringView()); if (write_exception.Raised()) { LOG(WARNING) << __func__ << ": Failed to write data: " << write_exception.value; diff --git a/connections/implementation/internal_payload.h b/connections/implementation/internal_payload.h index d70e0593..50b8ac73 100644 --- a/connections/implementation/internal_payload.h +++ b/connections/implementation/internal_payload.h @@ -15,9 +15,11 @@ #ifndef CORE_INTERNAL_INTERNAL_PAYLOAD_H_ #define CORE_INTERNAL_INTERNAL_PAYLOAD_H_ +#include #include #include +#include "absl/strings/string_view.h" #include "absl/time/time.h" #include "connections/implementation/proto/offline_wire_formats.pb.h" #include "connections/payload.h" @@ -82,14 +84,11 @@ class InternalPayload { // Adds the next chunk that comprises the Payload to which this object is // bound. // - //

Used when we are trying to reconstruct a Payload that lives on the - // other side of a hard boundary (like the other side of a Binder, or another - // device altogether), one byte blob at a time. + // Used when we are trying to reconstruct a Payload that lives on the + // other side of a hard boundary (like another device), one chunk at a time. // - // @param chunk The next chunk; this being null signals that this is the last - // chunk, which will typically be used as a trigger to perform whatever state - // cleanup may be required by the concrete implementation. - virtual Exception AttachNextChunk(const ByteArray& chunk) = 0; + // `chunk` is the next chunk. + virtual Exception AttachNextChunk(absl::string_view chunk) = 0; // Skips current stream pointer to the offset. // diff --git a/connections/implementation/internal_payload_factory.cc b/connections/implementation/internal_payload_factory.cc index f5b43333..8958ecc6 100644 --- a/connections/implementation/internal_payload_factory.cc +++ b/connections/implementation/internal_payload_factory.cc @@ -21,6 +21,7 @@ #include #include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "connections/implementation/internal_payload.h" @@ -73,7 +74,7 @@ class BytesInternalPayload : public InternalPayload { } // Does nothing. - Exception AttachNextChunk(const ByteArray& chunk) override { + Exception AttachNextChunk(absl::string_view chunk) override { return {Exception::kSuccess}; } @@ -127,7 +128,7 @@ class OutgoingStreamInternalPayload : public InternalPayload { return scoped_bytes_read; } - Exception AttachNextChunk(const ByteArray& chunk) override { + Exception AttachNextChunk(absl::string_view chunk) override { return {Exception::kIo}; } @@ -171,8 +172,8 @@ class IncomingStreamInternalPayload : public InternalPayload { ByteArray DetachNextChunk(int chunk_size) override { return {}; } - Exception AttachNextChunk(const ByteArray& chunk) override { - if (chunk.Empty()) { + Exception AttachNextChunk(absl::string_view chunk) override { + if (chunk.empty()) { LOG(INFO) << "Received null last chunk for incoming payload " << this << ", closing OutputStream."; Close(); @@ -229,7 +230,7 @@ class OutgoingFileInternalPayload : public InternalPayload { return bytes; } - Exception AttachNextChunk(const ByteArray& chunk) override { + Exception AttachNextChunk(absl::string_view chunk) override { return {Exception::kIo}; } @@ -285,8 +286,8 @@ class IncomingFileInternalPayload : public InternalPayload { ByteArray DetachNextChunk(int chunk_size) override { return {}; } - Exception AttachNextChunk(const ByteArray& chunk) override { - if (chunk.Empty()) { + Exception AttachNextChunk(absl::string_view chunk) override { + if (chunk.empty()) { // Received null last chunk for incoming payload. Close(); return {Exception::kSuccess}; diff --git a/connections/implementation/internal_payload_factory_test.cc b/connections/implementation/internal_payload_factory_test.cc index 2db1c760..dc72bd5c 100644 --- a/connections/implementation/internal_payload_factory_test.cc +++ b/connections/implementation/internal_payload_factory_test.cc @@ -21,6 +21,7 @@ #include #include "gtest/gtest.h" +#include "absl/strings/string_view.h" #include "connections/implementation/internal_payload.h" #include "connections/implementation/proto/offline_wire_formats.pb.h" #include "connections/payload.h" @@ -218,7 +219,8 @@ TEST(InternalPayloadFactoryTest, ASSERT_TRUE(result.has_error()); } -void CreateFileWithContents(Payload::Id payload_id, const ByteArray& contents) { +void CreateFileWithContents(Payload::Id payload_id, + absl::string_view contents) { OutputFile file(payload_id); EXPECT_TRUE(file.Write(contents).Ok()); EXPECT_TRUE(file.Close().Ok()); @@ -226,7 +228,7 @@ void CreateFileWithContents(Payload::Id payload_id, const ByteArray& contents) { TEST(InternalPayloadFactoryTest, SkipToOffset_FilePayloadValidOffset_SkipsOffset) { - ByteArray contents("0123456789"); + absl::string_view contents("0123456789"); constexpr size_t kOffset = 4; size_t size_after_skip = contents.size() - kOffset; Payload::Id payload_id = Payload::GenerateId(); @@ -251,7 +253,7 @@ TEST(InternalPayloadFactoryTest, TEST(InternalPayloadFactoryTest, SkipToOffset_StreamPayloadValidOffset_SkipsOffset) { - ByteArray contents("0123456789"); + absl::string_view contents("0123456789"); constexpr size_t kOffset = 6; auto [input, output] = CreatePipe(); ErrorOr> internal_payload_result = diff --git a/connections/implementation/mediums/BUILD b/connections/implementation/mediums/BUILD index cdb45d70..eb101d01 100644 --- a/connections/implementation/mediums/BUILD +++ b/connections/implementation/mediums/BUILD @@ -208,6 +208,7 @@ cc_test( "//internal/platform/implementation/g3", # build_cleaner: keep "//internal/test", "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_absl//absl/strings:string_view", "@com_google_googletest//:gtest_main", ], ) diff --git a/connections/implementation/mediums/ble/BUILD b/connections/implementation/mediums/ble/BUILD index a95faa6e..32655111 100644 --- a/connections/implementation/mediums/ble/BUILD +++ b/connections/implementation/mediums/ble/BUILD @@ -72,6 +72,7 @@ cc_library( "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/synchronization", ], ) diff --git a/connections/implementation/mediums/ble/ble_socket.cc b/connections/implementation/mediums/ble/ble_socket.cc index 51c0bd37..97c29e32 100644 --- a/connections/implementation/mediums/ble/ble_socket.cc +++ b/connections/implementation/mediums/ble/ble_socket.cc @@ -22,6 +22,7 @@ #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" #include "connections/implementation/flags/nearby_connections_feature_flags.h" #include "connections/implementation/mediums/ble/ble_l2cap_packet.h" #include "connections/implementation/mediums/ble/ble_packet.h" @@ -49,7 +50,7 @@ ExceptionOr BleInputStream::Read(std::int64_t size) { Exception BleInputStream::Close() { return source_.Close(); } -Exception BleOutputStream::Write(const ByteArray& data) { +Exception BleOutputStream::Write(absl::string_view data) { if (NearbyFlags::GetInstance().GetBoolFlag( config_package_nearby::nearby_connections_feature:: kRefactorBleL2cap)) { @@ -59,7 +60,7 @@ Exception BleOutputStream::Write(const ByteArray& data) { // Prepend the packet length to the data. std::string packet_str = absl::StrCat(std::string(byte_utils::IntToBytes(payload_length_)), - std::string(data)); + data); payload_length_ = 0; // Prepend the service id hash to the data with the payload length. @@ -69,7 +70,8 @@ Exception BleOutputStream::Write(const ByteArray& data) { if (!ble_packet_status_or.ok()) { return {Exception::kFailed}; } - return source_.Write(ByteArray(ble_packet_status_or.value())); + return source_.Write( + ByteArray(ble_packet_status_or.value()).AsStringView()); } else { return source_.Write(data); } @@ -80,7 +82,7 @@ Exception BleOutputStream::Flush() { return source_.Flush(); } Exception BleOutputStream::Close() { return source_.Close(); } Exception BleOutputStream::WriteControlPacket(const ByteArray& data) { - return source_.Write(data); + return source_.Write(data.AsStringView()); } Exception BleOutputStream::WritePayloadLength(int payload_length) { diff --git a/connections/implementation/mediums/ble/ble_socket.h b/connections/implementation/mediums/ble/ble_socket.h index 728b4f28..4aba0ca1 100644 --- a/connections/implementation/mediums/ble/ble_socket.h +++ b/connections/implementation/mediums/ble/ble_socket.h @@ -20,6 +20,7 @@ #include #include "absl/base/thread_annotations.h" +#include "absl/strings/string_view.h" #include "internal/platform/ble.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" @@ -98,11 +99,11 @@ class BleOutputStream : public OutputStream { * The resulting serialized `BlePacket` is then written to the `source_` * stream. * - * @param data The raw `ByteArray` payload to write to the stream. + * @param data The raw `absl::string_view` payload to write to the stream. * @return `Exception::kSuccess` if the write operation succeeds, or an * exception code indicating the type of error. */ - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/connections/implementation/mediums/ble/ble_socket_test.cc b/connections/implementation/mediums/ble/ble_socket_test.cc index 754a59b0..600d3774 100644 --- a/connections/implementation/mediums/ble/ble_socket_test.cc +++ b/connections/implementation/mediums/ble/ble_socket_test.cc @@ -77,11 +77,11 @@ class FakeInputStream : public InputStream { class FakeOutputStream : public OutputStream { public: - Exception Write(const ByteArray& data) override { + Exception Write(absl::string_view data) override { if (exception_on_write_) { return {Exception::kIo}; } - absl::StrAppend(&buffer_, std::string(data)); + absl::StrAppend(&buffer_, data); return {Exception::kSuccess}; } Exception Flush() override { return {Exception::kSuccess}; } @@ -283,7 +283,7 @@ TEST_F(BleSocketBleMediumTest, WritePayloadLengthSucceedsIfCalledAfterWrite) { config_package_nearby::nearby_connections_feature::kRefactorBleL2cap, true); constexpr int kPayloadLength = 12345; - ByteArray payload("payload"); + absl::string_view payload = "payload"; EXPECT_TRUE(socket_->WritePayloadLength(kPayloadLength).Ok()); EXPECT_TRUE(socket_->GetOutputStream().Write(payload).Ok()); EXPECT_TRUE(socket_->WritePayloadLength(kPayloadLength).Ok()); @@ -498,7 +498,7 @@ TEST_F(BleL2capSocketBleMediumTest, config_package_nearby::nearby_connections_feature::kRefactorBleL2cap, true); constexpr int kPayloadLength = 12345; - ByteArray payload("payload"); + absl::string_view payload = "payload"; EXPECT_TRUE(socket_->WritePayloadLength(kPayloadLength).Ok()); EXPECT_TRUE(socket_->GetOutputStream().Write(payload).Ok()); EXPECT_TRUE(socket_->WritePayloadLength(kPayloadLength).Ok()); diff --git a/connections/implementation/mediums/ble/bloom_filter.h b/connections/implementation/mediums/ble/bloom_filter.h index f33da62e..b038eafa 100644 --- a/connections/implementation/mediums/ble/bloom_filter.h +++ b/connections/implementation/mediums/ble/bloom_filter.h @@ -16,6 +16,11 @@ #define CORE_INTERNAL_MEDIUMS_BLE_BLOOM_FILTER_H_ #include +#include +#include +#include +#include +#include #include #include "internal/platform/byte_array.h" diff --git a/connections/implementation/mediums/multiplex/multiplex_frames.cc b/connections/implementation/mediums/multiplex/multiplex_frames.cc index 7e70cc52..3eea2aa1 100644 --- a/connections/implementation/mediums/multiplex/multiplex_frames.cc +++ b/connections/implementation/mediums/multiplex/multiplex_frames.cc @@ -17,6 +17,7 @@ #include #include +#include "absl/strings/string_view.h" #include "connections/implementation/mediums/utils.h" #include "internal/platform/base64_utils.h" #include "internal/platform/byte_array.h" @@ -121,7 +122,7 @@ ByteArray ForDisconnection(const std::string& service_id, ByteArray ForData(const std::string& service_id, const std::string& service_id_hash_salt, - bool should_pass_salt, const ByteArray& data) { + bool should_pass_salt, absl::string_view data) { MultiplexFrame frame; frame.set_frame_type(MultiplexFrame::DATA_FRAME); @@ -133,7 +134,7 @@ ByteArray ForData(const std::string& service_id, } auto* data_frame = frame.mutable_data_frame(); - data_frame->set_data(std::string(std::move(data))); + data_frame->set_data(data); return ToBytes(std::move(frame)); } diff --git a/connections/implementation/mediums/multiplex/multiplex_frames.h b/connections/implementation/mediums/multiplex/multiplex_frames.h index 2483c382..283697a4 100644 --- a/connections/implementation/mediums/multiplex/multiplex_frames.h +++ b/connections/implementation/mediums/multiplex/multiplex_frames.h @@ -18,6 +18,7 @@ #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "proto/mediums/multiplex_frames.pb.h" @@ -88,7 +89,7 @@ ByteArray ForDisconnection(const std::string& service_id, // @param data The data to send. ByteArray ForData(const std::string& service_id, const std::string& service_id_hash_salt, - bool should_pass_salt, const ByteArray& data); + bool should_pass_salt, absl::string_view data); ExceptionOr FromBytes( const ByteArray& multiplex_frame_bytes); diff --git a/connections/implementation/mediums/multiplex/multiplex_frames_test.cc b/connections/implementation/mediums/multiplex/multiplex_frames_test.cc index 238e02e8..95a66803 100644 --- a/connections/implementation/mediums/multiplex/multiplex_frames_test.cc +++ b/connections/implementation/mediums/multiplex/multiplex_frames_test.cc @@ -150,7 +150,7 @@ TEST(MultiplexFrameTest, CanGenerateDisconnection) { } TEST(MultiplexFrameTest, CanGenerateData) { - ByteArray data("abcdefghijklmnopqrstuvwxyz"); + absl::string_view data = "abcdefghijklmnopqrstuvwxyz"; ByteArray bytes = ForData(std::string(kServiceId_1), "1234", true, data); auto response = FromBytes(bytes); diff --git a/connections/implementation/mediums/multiplex/multiplex_output_stream.cc b/connections/implementation/mediums/multiplex/multiplex_output_stream.cc index 20957ded..0cdc2d52 100644 --- a/connections/implementation/mediums/multiplex/multiplex_output_stream.cc +++ b/connections/implementation/mediums/multiplex/multiplex_output_stream.cc @@ -246,13 +246,12 @@ void MultiplexOutputStream::MultiplexWriter::StartWriting() { void MultiplexOutputStream::MultiplexWriter::Write( EnqueuedFrame& enqueued_frame) { MutexLock lock(&writer_mutex_); - if (!physical_writer_ - ->Write(Base64Utils::IntToBytes(enqueued_frame.data_.size())) + if (!Base64Utils::WriteInt(physical_writer_, enqueued_frame.data_.size()) .Ok()) { enqueued_frame.future_->SetException({Exception::kIo}); return; }; - if (!physical_writer_->Write(enqueued_frame.data_).Ok()) { + if (!physical_writer_->Write(enqueued_frame.data_.AsStringView()).Ok()) { enqueued_frame.future_->SetException({Exception::kIo}); return; }; @@ -301,7 +300,7 @@ MultiplexOutputStream::VirtualOutputStream::VirtualOutputStream( multiplex_output_stream_(multiplex_output_stream) {} Exception MultiplexOutputStream::VirtualOutputStream::Write( - const ByteArray& data) { + absl::string_view data) { if (is_closed_.Get()) { LOG(WARNING) << "Failed to write data because the VirtualOutputStream for " << service_id_ << " closed"; diff --git a/connections/implementation/mediums/multiplex/multiplex_output_stream.h b/connections/implementation/mediums/multiplex/multiplex_output_stream.h index b711fcb5..22067d71 100644 --- a/connections/implementation/mediums/multiplex/multiplex_output_stream.h +++ b/connections/implementation/mediums/multiplex/multiplex_output_stream.h @@ -20,6 +20,7 @@ #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" #include "internal/platform/array_blocking_queue.h" #include "internal/platform/atomic_boolean.h" #include "internal/platform/byte_array.h" @@ -174,7 +175,7 @@ class MultiplexOutputStream { } // Writes the data to the physical output stream. - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; // Flushes the physical output stream. Exception Flush() override; // Closes the virtual output stream. diff --git a/connections/implementation/mediums/multiplex/multiplex_output_stream_test.cc b/connections/implementation/mediums/multiplex/multiplex_output_stream_test.cc index 96f54ddd..4a5ae130 100644 --- a/connections/implementation/mediums/multiplex/multiplex_output_stream_test.cc +++ b/connections/implementation/mediums/multiplex/multiplex_output_stream_test.cc @@ -173,7 +173,7 @@ TEST_F(MultiplexOutputStreamTest, CreateVirtualStream_SendData) { multiplex_output_stream_->CreateVirtualOutputStream( std::string(kServiceId_1), std::string(kSalt_1)); - const ByteArray data("abcdefghijklmnopqrstuvwxyz"); + absl::string_view data = "abcdefghijklmnopqrstuvwxyz"; virtual_output_stream->Write(data); virtual_output_stream->Flush(); auto frame_data = ReadFrame(); @@ -199,8 +199,8 @@ TEST_F(MultiplexOutputStreamTest, CreateTwoVirtualStreams_SendData) { multiplex_output_stream_->CreateVirtualOutputStreamForFirstVirtualSocket( std::string(kServiceId_2), std::string(kSalt_2)); - const ByteArray data_1("abcdefg"); - const ByteArray data_2("hijklmn"); + absl::string_view data_1("abcdefg"); + absl::string_view data_2("hijklmn"); MultiThreadExecutor executor(2); CountDownLatch latch(2); executor.Execute([&virtual_output_stream_1, &latch, &data_1]() { diff --git a/connections/implementation/mediums/multiplex/multiplex_socket_test.cc b/connections/implementation/mediums/multiplex/multiplex_socket_test.cc index b798340a..3b523d20 100644 --- a/connections/implementation/mediums/multiplex/multiplex_socket_test.cc +++ b/connections/implementation/mediums/multiplex/multiplex_socket_test.cc @@ -199,8 +199,8 @@ TEST(MultiplexSocketTest, CreateIncomingSocketSuccess) { }); auto& writer = socket->writer_1_; LOG(INFO) << "writer_1_ Write start"; - writer->Write(Base64Utils::IntToBytes(connection_req_frame.size())); - writer->Write(connection_req_frame); + Base64Utils::WriteInt(writer.get(), connection_req_frame.size()); + writer->Write(connection_req_frame.AsStringView()); writer->Flush(); LOG(INFO) << "writer_1_ Write end"; }); @@ -269,8 +269,8 @@ TEST(MultiplexSocketTest, CreateIncomingVirtualSocketSuccess) { std::string(SERVICE_ID_2), "J7frzSmHK-VBTHjCKpf4ew"); auto& writer = socket->writer_1_; LOG(INFO) << "writer_1_ Write start"; - writer->Write(Base64Utils::IntToBytes(connection_req_frame.size())); - writer->Write(connection_req_frame); + Base64Utils::WriteInt(writer.get(), connection_req_frame.size()); + writer->Write(connection_req_frame.AsStringView()); writer->Flush(); LOG(INFO) << "writer_1_ Write end"; }); @@ -414,8 +414,8 @@ TEST(MultiplexSocketTest, EstablishVirtualSocket_RemoteAccepted) { ConnectionResponseFrame::CONNECTION_ACCEPTED); auto& writer = fake_socket_ptr->writer_1_; LOG(INFO) << "writer_1_ Write start"; - writer->Write(Base64Utils::IntToBytes(connection_response_frame.size())); - writer->Write(connection_response_frame); + Base64Utils::WriteInt(writer.get(), connection_response_frame.size()); + writer->Write(connection_response_frame.AsStringView()); writer->Flush(); LOG(INFO) << "writer_1_ Write end"; absl::SleepFor(absl::Milliseconds(100)); @@ -427,17 +427,17 @@ TEST(MultiplexSocketTest, EstablishVirtualSocket_RemoteAccepted) { LOG(INFO) << "Send Data frame on virtual socket for SERVICE_ID_2."; ByteArray data_frame = ForData(std::string(SERVICE_ID_2), service_id_hash_salt, - /*should_pass_salt=*/true, ByteArray("data")); - writer->Write(Base64Utils::IntToBytes(data_frame.size())); - writer->Write(data_frame); + /*should_pass_salt=*/true, absl::string_view("data")); + Base64Utils::WriteInt(writer.get(), data_frame.size()); + writer->Write(data_frame.AsStringView()); writer->Flush(); absl::SleepFor(absl::Milliseconds(100)); LOG(INFO) << "Send disconnection frame on virtual socket for SERVICE_ID_2."; ByteArray disconnect_frame = ForDisconnection(std::string(SERVICE_ID_2), service_id_hash_salt); - writer->Write(Base64Utils::IntToBytes(disconnect_frame.size())); - writer->Write(disconnect_frame); + Base64Utils::WriteInt(writer.get(), disconnect_frame.size()); + writer->Write(disconnect_frame.AsStringView()); writer->Flush(); absl::SleepFor(absl::Milliseconds(100)); EXPECT_EQ(multiplex_socket->GetVirtualSocketCount(), 1); diff --git a/connections/implementation/mediums/webrtc/BUILD b/connections/implementation/mediums/webrtc/BUILD index df602ddd..5e52c310 100644 --- a/connections/implementation/mediums/webrtc/BUILD +++ b/connections/implementation/mediums/webrtc/BUILD @@ -72,6 +72,7 @@ cc_library( "//internal/platform:base", "//internal/platform:logging", "//internal/platform:types", + "@com_google_absl//absl/strings:string_view", ], ) @@ -100,6 +101,7 @@ cc_test( "//third_party/webrtc/files/stable/webrtc/api:libjingle_peerconnection_api", "//third_party/webrtc/files/stable/webrtc/api:scoped_refptr", "@com_github_protobuf_matchers//protobuf-matchers", + "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/time", "@com_google_googletest//:gtest_main", ], diff --git a/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc b/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc index bd1b1338..aca93c67 100644 --- a/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc +++ b/connections/implementation/mediums/webrtc/webrtc_socket_impl.cc @@ -17,6 +17,7 @@ #include #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/input_stream.h" @@ -32,7 +33,7 @@ namespace connections { namespace mediums { // OutputStreamImpl -Exception WebRtcSocket::OutputStreamImpl::Write(const ByteArray& data) { +Exception WebRtcSocket::OutputStreamImpl::Write(absl::string_view data) { if (data.size() > kMaxDataSize) { LOG(WARNING) << "Sending data larger than 1MB"; return {Exception::kIo}; @@ -45,7 +46,7 @@ Exception WebRtcSocket::OutputStreamImpl::Write(const ByteArray& data) { return {Exception::kIo}; } - if (!socket_->SendMessage(data)) { + if (!socket_->SendMessage(ByteArray::FromStringView(data))) { LOG(INFO) << "Unable to write data to socket."; return {Exception::kIo}; } @@ -135,7 +136,7 @@ void WebRtcSocket::OnMessage(const webrtc::DataBuffer& buffer) { // we don't block signaling. OffloadFromSignalingThread( [this, buffer = ByteArray(buffer.data.data(), buffer.size())] { - if (!pipe_output_->Write(buffer).Ok()) { + if (!pipe_output_->Write(buffer.AsStringView()).Ok()) { Close(); return; } diff --git a/connections/implementation/mediums/webrtc/webrtc_socket_impl.h b/connections/implementation/mediums/webrtc/webrtc_socket_impl.h index 6a4efe7f..109367b7 100644 --- a/connections/implementation/mediums/webrtc/webrtc_socket_impl.h +++ b/connections/implementation/mediums/webrtc/webrtc_socket_impl.h @@ -19,6 +19,7 @@ #include #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/listeners.h" @@ -84,7 +85,7 @@ class WebRtcSocket : public Socket, public webrtc::DataChannelObserver { OutputStreamImpl& operator=(const OutputStreamImpl& other) = delete; // OutputStream: - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc b/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc index 0be71e94..78ec1771 100644 --- a/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc +++ b/connections/implementation/mediums/webrtc/webrtc_socket_impl_test.cc @@ -20,6 +20,7 @@ #include "gmock/gmock.h" #include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "webrtc/api/data_channel_interface.h" @@ -97,7 +98,7 @@ TEST(WebRtcSocketTest, ReadMultipleMessages) { } TEST(WebRtcSocketTest, WriteToSocket) { - const ByteArray kMessage{"Message"}; + absl::string_view kMessage{"Message"}; webrtc::scoped_refptr mock_data_channel( new MockDataChannel()); WebRtcSocket webrtc_socket(kSocketName, mock_data_channel); @@ -108,7 +109,7 @@ TEST(WebRtcSocketTest, WriteToSocket) { } TEST(WebRtcSocketTest, SendDataBiggerThanMax) { - const ByteArray kMessage{kMaxDataSize + 1}; + std::string kMessage(kMaxDataSize + 1, '0'); webrtc::scoped_refptr mock_data_channel( new MockDataChannel()); WebRtcSocket webrtc_socket(kSocketName, mock_data_channel); @@ -119,7 +120,7 @@ TEST(WebRtcSocketTest, SendDataBiggerThanMax) { } TEST(WebRtcSocketTest, WriteToDataChannelFails) { - ByteArray kMessage{"Message"}; + absl::string_view kMessage{"Message"}; webrtc::scoped_refptr mock_data_channel( new MockDataChannel()); WebRtcSocket webrtc_socket(kSocketName, mock_data_channel); @@ -156,7 +157,7 @@ TEST(WebRtcSocketTest, Close) { } TEST(WebRtcSocketTest, WriteOnClosedChannel) { - ByteArray kMessage{"Message"}; + absl::string_view kMessage{"Message"}; webrtc::scoped_refptr mock_data_channel( new MockDataChannel()); WebRtcSocket webrtc_socket(kSocketName, mock_data_channel); @@ -168,7 +169,7 @@ TEST(WebRtcSocketTest, WriteOnClosedChannel) { } TEST(WebRtcSocketTest, ReadFromClosedChannel) { - ByteArray kMessage{"Message"}; + absl::string_view kMessage{"Message"}; webrtc::scoped_refptr mock_data_channel( new MockDataChannel()); WebRtcSocket webrtc_socket(kSocketName, mock_data_channel); diff --git a/connections/implementation/mediums/webrtc_socket_stub.h b/connections/implementation/mediums/webrtc_socket_stub.h index 8cecff4e..f3f104ef 100644 --- a/connections/implementation/mediums/webrtc_socket_stub.h +++ b/connections/implementation/mediums/webrtc_socket_stub.h @@ -35,7 +35,7 @@ class FakeInputStream : public InputStream { class FakeOutputStream : public OutputStream { public: - Exception Write(const ByteArray& data) override { + Exception Write(absl::string_view data) override { return {Exception::kSuccess}; } Exception Flush() override { return {Exception::kSuccess}; } diff --git a/connections/implementation/payload_manager.cc b/connections/implementation/payload_manager.cc index bf71e788..2ff3e716 100644 --- a/connections/implementation/payload_manager.cc +++ b/connections/implementation/payload_manager.cc @@ -1415,7 +1415,7 @@ void PayloadManager::ProcessDataPacket( packet_meta_data.StartFileIo(); if (pending_payload->GetInternalPayload() - ->AttachNextChunk(ByteArray(std::move(*payload_chunk.mutable_body()))) + ->AttachNextChunk(payload_chunk.body()) .Raised()) { LOG(ERROR) << "ProcessDataPacket: [data: error] endpoint_id=" << from_endpoint_id diff --git a/connections/implementation/payload_manager_test.cc b/connections/implementation/payload_manager_test.cc index 98d7ceaa..6605112c 100644 --- a/connections/implementation/payload_manager_test.cc +++ b/connections/implementation/payload_manager_test.cc @@ -31,6 +31,7 @@ #include "internal/platform/byte_array.h" #include "internal/platform/count_down_latch.h" #include "internal/platform/exception.h" +#include "internal/platform/implementation/system_clock.h" #include "internal/platform/input_stream.h" #include "internal/platform/logging.h" #include "internal/platform/medium_environment.h" @@ -221,10 +222,9 @@ TEST_P(PayloadManagerTest, CanSendStreamPayload) { auto [input, tx] = CreatePipe(); user_a.ExpectPayload(payload_latch_); - const ByteArray message{std::string(kMessage)}; // The first write to the output stream will send the first PAYLOAD_TRANSFER // packet with payload info and message data. - tx->Write(message); + tx->Write(kMessage); user_b.SendPayload(Payload(std::move(input))); ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result()); @@ -233,22 +233,22 @@ TEST_P(PayloadManagerTest, CanSendStreamPayload) { LOG(INFO) << "Stream extracted."; EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= message.size(); + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= kMessage.size(); }, kProgressTimeout)); ByteArray result = rx.Read(kChunkSize).result(); - EXPECT_EQ(result, message); + EXPECT_EQ(result.AsStringView(), kMessage); LOG(INFO) << "Packet 1 handled."; - tx->Write(message); + tx->Write(kMessage); EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= 2 * message.size(); + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= 2 * kMessage.size(); }, kProgressTimeout)); ByteArray result2 = rx.Read(kChunkSize).result(); - EXPECT_EQ(result2, message); + EXPECT_EQ(result2.AsStringView(), kMessage); LOG(INFO) << "Packet 2 handled."; rx.Close(); @@ -266,8 +266,7 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnReceiverSide) { ASSERT_TRUE(SetupConnection(user_a, user_b)); auto [input, tx] = CreatePipe(); user_a.ExpectPayload(payload_latch_); - const ByteArray message{std::string(kMessage)}; - tx->Write(message); + tx->Write(kMessage); user_b.SendPayload(Payload(std::move(input))); ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result()); @@ -276,12 +275,12 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnReceiverSide) { LOG(INFO) << "Stream extracted."; EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= message.size(); + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= kMessage.size(); }, kProgressTimeout)); ByteArray result = rx.Read(kChunkSize).result(); - EXPECT_EQ(result, message); + EXPECT_EQ(result.AsStringView(), kMessage); LOG(INFO) << "Packet 1 handled."; EXPECT_EQ(user_a.CancelPayload(), Status{Status::kSuccess}); @@ -291,7 +290,7 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnReceiverSide) { // Once cancel is handled, write will fail. int count = 0; while (true) { - if (!tx->Write(message).Ok()) break; + if (!tx->Write(kMessage).Ok()) break; SystemClock::Sleep(kDefaultTimeout); count++; } @@ -319,8 +318,7 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnSenderSide) { ASSERT_TRUE(SetupConnection(user_a, user_b)); auto [input, tx] = CreatePipe(); user_a.ExpectPayload(payload_latch_); - const ByteArray message{std::string(kMessage)}; - tx->Write(message); + tx->Write(kMessage); user_b.SendPayload(Payload(std::move(input))); ASSERT_TRUE(payload_latch_.Await(kDefaultTimeout).result()); @@ -329,12 +327,12 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnSenderSide) { LOG(INFO) << "Stream extracted."; EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= message.size(); + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= kMessage.size(); }, kProgressTimeout)); ByteArray result = rx.Read(kChunkSize).result(); - EXPECT_EQ(result, message); + EXPECT_EQ(result.AsStringView(), kMessage); LOG(INFO) << "Packet 1 handled."; EXPECT_EQ(user_b.CancelPayload(), Status{Status::kSuccess}); @@ -344,7 +342,7 @@ TEST_P(PayloadManagerTest, CanCancelPayloadOnSenderSide) { // Once cancel is handled, write will fail. int count = 0; while (true) { - if (!tx->Write(message).Ok()) break; + if (!tx->Write(kMessage).Ok()) break; SystemClock::Sleep(kDefaultTimeout); count++; } @@ -373,10 +371,9 @@ TEST_P(PayloadManagerTest, SendPayloadWithSkip_StreamPayload) { ASSERT_TRUE(SetupConnection(user_a, user_b)); auto [input, tx] = CreatePipe(); user_a.ExpectPayload(payload_latch_); - const ByteArray message{std::string(kMessage)}; // The first write to the output stream will send the first PAYLOAD_TRANSFER // packet with payload info and message data. - tx->Write(message); + tx->Write(kMessage); Payload payload(std::move(input)); payload.SetOffset(kOffset); @@ -387,22 +384,22 @@ TEST_P(PayloadManagerTest, SendPayloadWithSkip_StreamPayload) { LOG(INFO) << "Stream extracted."; EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= message.size() - kOffset; + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= kMessage.size() - kOffset; }, kProgressTimeout)); ByteArray result = rx.Read(kChunkSize).result(); EXPECT_EQ(result, ByteArray("sage")); LOG(INFO) << "Packet 1 handled."; - tx->Write(message); + tx->Write(kMessage); EXPECT_TRUE(user_a.WaitForProgress( - [&message](const PayloadProgressInfo& info) { - return info.bytes_transferred >= 2 * message.size() - kOffset; + [](const PayloadProgressInfo& info) { + return info.bytes_transferred >= 2 * kMessage.size() - kOffset; }, kProgressTimeout)); ByteArray result2 = rx.Read(kChunkSize).result(); - EXPECT_EQ(result2, message); + EXPECT_EQ(result2.AsStringView(), kMessage); LOG(INFO) << "Packet 2 handled."; rx.Close(); @@ -417,8 +414,7 @@ TEST_P(PayloadManagerTest, OfflineFrame_BeforeConnected_ShouldDrop) { env_.Start(); PayloadSimulationUser user(kDeviceB, GetParam()); auto [input, tx] = CreatePipe(); - const ByteArray message{std::string(kMessage)}; - tx->Write(message); + tx->Write(kMessage); Payload payload(std::move(input)); user.ReceivePayload(std::move(payload), "1234"); ASSERT_EQ(user.GetPayload().AsStream(), nullptr); diff --git a/connections/payload_test.cc b/connections/payload_test.cc index c7307bbb..3c31f762 100644 --- a/connections/payload_test.cc +++ b/connections/payload_test.cc @@ -14,13 +14,15 @@ #include "connections/payload.h" +#include #include +#include #include #include -#include "gmock/gmock.h" -#include "protobuf-matchers/protocol-buffer-matchers.h" #include "gtest/gtest.h" +#include "absl/strings/string_view.h" +#include "connections/payload_type.h" #include "internal/platform/byte_array.h" #include "internal/platform/file.h" #include "internal/platform/input_stream.h" @@ -47,15 +49,12 @@ TEST(PayloadTest, SupportsFileType) { constexpr size_t kOffset = 99; const auto payload_id = Payload::GenerateId(); - char test_file_data[100]; - memcpy(test_file_data, + absl::string_view test_file_data{ "012345678901234567890123456789012345678901234567890123456789012345678" - "901234567890123456789012345678\0", - 100); + "901234567890123456789012345678\0", 100}; OutputFile outputFile(payload_id); - ByteArray test_data(test_file_data, 100); - outputFile.Write(test_data); + outputFile.Write(test_file_data); outputFile.Close(); InputFile file(payload_id); diff --git a/internal/platform/BUILD b/internal/platform/BUILD index 38432d23..39ccdd72 100644 --- a/internal/platform/BUILD +++ b/internal/platform/BUILD @@ -84,6 +84,7 @@ cc_library( "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", ], @@ -411,6 +412,7 @@ cc_library( ":base", ":cancellation_flag", "//internal/platform/implementation:comm", + "@com_google_absl//absl/strings:string_view", "@com_google_absl//absl/types:optional", "@com_google_googletest//:gtest_for_library_testonly", ], diff --git a/internal/platform/base64_utils.cc b/internal/platform/base64_utils.cc index b4834d0e..e3e9d92d 100644 --- a/internal/platform/base64_utils.cc +++ b/internal/platform/base64_utils.cc @@ -48,20 +48,20 @@ std::int32_t Base64Utils::BytesToInt(const ByteArray& bytes) { const char* int_bytes = bytes.data(); std::int32_t result = 0; - result |= (static_cast(int_bytes[0]) & 0x0FF) << 24; - result |= (static_cast(int_bytes[1]) & 0x0FF) << 16; - result |= (static_cast(int_bytes[2]) & 0x0FF) << 8; - result |= (static_cast(int_bytes[3]) & 0x0FF); + result |= (static_cast(int_bytes[0]) & 0xFF) << 24; + result |= (static_cast(int_bytes[1]) & 0xFF) << 16; + result |= (static_cast(int_bytes[2]) & 0xFF) << 8; + result |= (static_cast(int_bytes[3]) & 0xFF); return result; } ByteArray Base64Utils::IntToBytes(std::int32_t value) { char int_bytes[sizeof(std::int32_t)]; - int_bytes[0] = static_cast((value >> 24) & 0x0FF); - int_bytes[1] = static_cast((value >> 16) & 0x0FF); - int_bytes[2] = static_cast((value >> 8) & 0x0FF); - int_bytes[3] = static_cast((value) & 0x0FF); + int_bytes[0] = static_cast((value >> 24) & 0xFF); + int_bytes[1] = static_cast((value >> 16) & 0xFF); + int_bytes[2] = static_cast((value >> 8) & 0xFF); + int_bytes[3] = static_cast((value) & 0xFF); return ByteArray(int_bytes, sizeof(int_bytes)); } @@ -71,12 +71,15 @@ ExceptionOr Base64Utils::ReadInt(InputStream* reader) { if (!read_bytes.ok()) { return ExceptionOr(read_bytes.exception()); } - return ExceptionOr( - BytesToInt(std::move(read_bytes.result()))); + return ExceptionOr(BytesToInt(std::move(read_bytes.result()))); } Exception Base64Utils::WriteInt(OutputStream* writer, std::int32_t value) { - return writer->Write(IntToBytes(value)); + std::string bytes = {static_cast((value >> 24) & 0xFF), + static_cast((value >> 16) & 0xFF), + static_cast((value >> 8) & 0xFF), + static_cast((value) & 0xFF)}; + return writer->Write(bytes); } } // namespace nearby diff --git a/internal/platform/byte_array.h b/internal/platform/byte_array.h index 2951c04f..fa134ac9 100644 --- a/internal/platform/byte_array.h +++ b/internal/platform/byte_array.h @@ -18,12 +18,9 @@ #include #include #include -#include #include #include -#include "absl/status/status.h" -#include "absl/status/statusor.h" #include "absl/strings/string_view.h" namespace nearby { @@ -33,6 +30,10 @@ class ByteArray { using iterator = std::string::iterator; using const_iterator = std::string::const_iterator; + static ByteArray FromStringView(absl::string_view source) { + return ByteArray(source.data(), source.size()); + } + // Create an empty ByteArray ByteArray() = default; template diff --git a/internal/platform/file.cc b/internal/platform/file.cc index 9dbf1766..a69e97d8 100644 --- a/internal/platform/file.cc +++ b/internal/platform/file.cc @@ -16,6 +16,7 @@ #include #include #include +#include "absl/strings/string_view.h" #include "absl/time/time.h" #include "internal/platform/payload_id.h" @@ -70,9 +71,9 @@ OutputFile::OutputFile(OutputFile&&) noexcept = default; OutputFile& OutputFile::operator=(OutputFile&&) = default; bool OutputFile::IsValid() const { return impl_ != nullptr; } -// Writes all data from ByteArray object to the underlying stream. +// Writes all data from absl::string_view to the underlying stream. // Returns Exception::kIo on error, Exception::kSuccess otherwise. -Exception OutputFile::Write(const ByteArray& data) { +Exception OutputFile::Write(absl::string_view data) { return impl_->Write(data); } diff --git a/internal/platform/file.h b/internal/platform/file.h index 042fec09..d917c024 100644 --- a/internal/platform/file.h +++ b/internal/platform/file.h @@ -20,6 +20,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/time/time.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" @@ -84,9 +85,9 @@ class OutputFile final { bool IsValid() const; - // Writes all data from ByteArray object to the underlying stream. + // Writes all data from string_view object to the underlying stream. // Returns Exception::kIo on error, Exception::kSuccess otherwise. - Exception Write(const ByteArray& data); + Exception Write(absl::string_view data); // Disallows further writes to the file and frees system resources, // associated with it. diff --git a/internal/platform/file_test.cc b/internal/platform/file_test.cc index a9470018..dbc6138d 100644 --- a/internal/platform/file_test.cc +++ b/internal/platform/file_test.cc @@ -46,7 +46,7 @@ TEST_F(FileTest, ConstructorDestructorWorks) { // Create an output file and write to it. OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - output_file.Write(ByteArray(data)); + output_file.Write(data); output_file.Close(); // Create an input file and read from it. @@ -64,7 +64,7 @@ TEST_F(FileTest, SimpleWriteRead) { // Write to file. OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(data)).Ok()); + EXPECT_TRUE(output_file.Write(data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); // Read from file. @@ -82,7 +82,7 @@ TEST_F(FileTest, WriteThenCloseThenRead) { // Write and close. OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(data)).Ok()); + EXPECT_TRUE(output_file.Write(data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); // Re-open and read. @@ -115,7 +115,7 @@ TEST_F(FileTest, ReadExactly) { OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(data)).Ok()); + EXPECT_TRUE(output_file.Write(data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); InputFile input_file(file_path.ToString()); @@ -132,7 +132,7 @@ TEST_F(FileTest, ReadTooMuch) { OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(data)).Ok()); + EXPECT_TRUE(output_file.Write(data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); InputFile input_file(file_path.ToString()); @@ -150,7 +150,7 @@ TEST_F(FileTest, Skip) { OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(full_data)).Ok()); + EXPECT_TRUE(output_file.Write(full_data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); InputFile input_file(file_path.ToString()); @@ -172,8 +172,8 @@ TEST_F(FileTest, MultipleWrites) { OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(data1)).Ok()); - EXPECT_TRUE(output_file.Write(ByteArray(data2)).Ok()); + EXPECT_TRUE(output_file.Write(data1).Ok()); + EXPECT_TRUE(output_file.Write(data2).Ok()); EXPECT_TRUE(output_file.Close().Ok()); InputFile input_file(file_path.ToString()); @@ -205,7 +205,7 @@ TEST_F(FileTest, WriteLargeFile) { OutputFile output_file(file_path.ToString()); ASSERT_TRUE(output_file.IsValid()); - EXPECT_TRUE(output_file.Write(ByteArray(large_data)).Ok()); + EXPECT_TRUE(output_file.Write(large_data).Ok()); EXPECT_TRUE(output_file.Close().Ok()); InputFile input_file(file_path.ToString()); diff --git a/internal/platform/implementation/apple/Tests/ble_socket_test.mm b/internal/platform/implementation/apple/Tests/ble_socket_test.mm index d18f1b73..b61e5a2c 100644 --- a/internal/platform/implementation/apple/Tests/ble_socket_test.mm +++ b/internal/platform/implementation/apple/Tests/ble_socket_test.mm @@ -124,7 +124,7 @@ - (void)testBleOutputStreamWrite { nearby::apple::BleOutputStream &outputStream = _socket->GetOutputStream(); - nearby::ByteArray data("test"); + absl::string_view data("test"); XCTAssertEqual(outputStream.Write(data).value, nearby::Exception::kSuccess); } diff --git a/internal/platform/implementation/apple/awdl.h b/internal/platform/implementation/apple/awdl.h index f450f00e..2949c25f 100644 --- a/internal/platform/implementation/apple/awdl.h +++ b/internal/platform/implementation/apple/awdl.h @@ -51,7 +51,7 @@ class AwdlOutputStream : public OutputStream { explicit AwdlOutputStream(GNCNWFrameworkSocket* socket); ~AwdlOutputStream() override = default; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/internal/platform/implementation/apple/awdl.mm b/internal/platform/implementation/apple/awdl.mm index 71942b68..f23b61b5 100644 --- a/internal/platform/implementation/apple/awdl.mm +++ b/internal/platform/implementation/apple/awdl.mm @@ -53,7 +53,7 @@ Exception AwdlInputStream::Close() { AwdlOutputStream::AwdlOutputStream(GNCNWFrameworkSocket* socket) : socket_(socket) {} -Exception AwdlOutputStream::Write(const ByteArray& data) { +Exception AwdlOutputStream::Write(absl::string_view data) { NSError* error = nil; BOOL result = [socket_ write:[NSData dataWithBytes:data.data() length:data.size()] error:&error]; if (!result) { diff --git a/internal/platform/implementation/apple/ble_l2cap_socket.h b/internal/platform/implementation/apple/ble_l2cap_socket.h index 2a95ad62..6ec51813 100644 --- a/internal/platform/implementation/apple/ble_l2cap_socket.h +++ b/internal/platform/implementation/apple/ble_l2cap_socket.h @@ -58,7 +58,7 @@ class BleL2capOutputStream : public OutputStream { // Write the provided bytes to the output stream. // // Returns Exception::kIo on error, otherwise Exception::kSuccess. - Exception Write(const ByteArray &data) override; + Exception Write(absl::string_view data) override; // no-op // diff --git a/internal/platform/implementation/apple/ble_l2cap_socket.mm b/internal/platform/implementation/apple/ble_l2cap_socket.mm index 170764c4..c8176979 100644 --- a/internal/platform/implementation/apple/ble_l2cap_socket.mm +++ b/internal/platform/implementation/apple/ble_l2cap_socket.mm @@ -104,7 +104,7 @@ BleL2capOutputStream::~BleL2capOutputStream() { NSCAssert(!connection_, @"BleL2capOutputStream not closed before destruction"); } -Exception BleL2capOutputStream::Write(const ByteArray &data) { +Exception BleL2capOutputStream::Write(absl::string_view data) { [condition_ lock]; if (!connection_) { [condition_ unlock]; diff --git a/internal/platform/implementation/apple/ble_medium.mm b/internal/platform/implementation/apple/ble_medium.mm index f82df304..ef458c36 100644 --- a/internal/platform/implementation/apple/ble_medium.mm +++ b/internal/platform/implementation/apple/ble_medium.mm @@ -631,7 +631,7 @@ std::unique_ptr BleMedium::Connect( if (!GNCFeatureFlags.refactorBleL2capEnabled) { // Send the (empty) intro packet, which the BLE advertiser is expecting. - socket->GetOutputStream().Write(ByteArray()); + socket->GetOutputStream().Write(""); } return std::move(socket); } diff --git a/internal/platform/implementation/apple/ble_socket.h b/internal/platform/implementation/apple/ble_socket.h index e0ee8ad4..b4d947c5 100644 --- a/internal/platform/implementation/apple/ble_socket.h +++ b/internal/platform/implementation/apple/ble_socket.h @@ -70,7 +70,7 @@ class BleOutputStream : public OutputStream { // Write the provided bytes to the output stream. // // Returns Exception::kIo on error, otherwise Exception::kSuccess. - Exception Write(const ByteArray &data) override; + Exception Write(absl::string_view data) override; // no-op // diff --git a/internal/platform/implementation/apple/ble_socket.mm b/internal/platform/implementation/apple/ble_socket.mm index 29fe7917..c1557c0e 100644 --- a/internal/platform/implementation/apple/ble_socket.mm +++ b/internal/platform/implementation/apple/ble_socket.mm @@ -112,14 +112,14 @@ BleOutputStream::~BleOutputStream() { NSCAssert(!connection_, @"BleOutputStream not closed before destruction"); } -Exception BleOutputStream::Write(const ByteArray &data) { +Exception BleOutputStream::Write(absl::string_view data) { [condition_ lock]; if (!connection_) { [condition_ unlock]; return {Exception::kIo}; } - NSMutableData *packet = [NSMutableData dataWithData:NSDataFromByteArray(data)]; + NSMutableData *packet = [NSMutableData dataWithBytes:data.data() length:data.size()]; // Send the data, blocking until the completion handler is called. __block bool isComplete = NO; diff --git a/internal/platform/implementation/apple/wifi_hotspot.h b/internal/platform/implementation/apple/wifi_hotspot.h index 325008e4..571ef73e 100644 --- a/internal/platform/implementation/apple/wifi_hotspot.h +++ b/internal/platform/implementation/apple/wifi_hotspot.h @@ -55,7 +55,7 @@ class WifiHotspotOutputStream : public OutputStream { explicit WifiHotspotOutputStream(GNCNWFrameworkSocket* socket); ~WifiHotspotOutputStream() override = default; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/internal/platform/implementation/apple/wifi_hotspot.mm b/internal/platform/implementation/apple/wifi_hotspot.mm index d2236f88..0ec2e846 100644 --- a/internal/platform/implementation/apple/wifi_hotspot.mm +++ b/internal/platform/implementation/apple/wifi_hotspot.mm @@ -61,7 +61,7 @@ Exception WifiHotspotInputStream::Close() { WifiHotspotOutputStream::WifiHotspotOutputStream(GNCNWFrameworkSocket* socket) : socket_(socket) {} -Exception WifiHotspotOutputStream::Write(const ByteArray& data) { +Exception WifiHotspotOutputStream::Write(absl::string_view data) { NSError* error = nil; BOOL result = [socket_ write:[NSData dataWithBytes:data.data() length:data.size()] error:&error]; if (!result) { diff --git a/internal/platform/implementation/apple/wifi_lan.h b/internal/platform/implementation/apple/wifi_lan.h index 41e4acc0..192cb0a8 100644 --- a/internal/platform/implementation/apple/wifi_lan.h +++ b/internal/platform/implementation/apple/wifi_lan.h @@ -21,6 +21,7 @@ #include #include +#include "absl/strings/string_view.h" #include "internal/platform/implementation/upgrade_address_info.h" #include "internal/platform/implementation/wifi_lan.h" #include "internal/platform/nsd_service_info.h" @@ -56,7 +57,7 @@ class WifiLanOutputStream : public OutputStream { explicit WifiLanOutputStream(GNCNWFrameworkSocket* socket); ~WifiLanOutputStream() override = default; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/internal/platform/implementation/apple/wifi_lan.mm b/internal/platform/implementation/apple/wifi_lan.mm index a3bb8a84..5f57ba52 100644 --- a/internal/platform/implementation/apple/wifi_lan.mm +++ b/internal/platform/implementation/apple/wifi_lan.mm @@ -53,7 +53,7 @@ Exception WifiLanInputStream::Close() { WifiLanOutputStream::WifiLanOutputStream(GNCNWFrameworkSocket* socket) : socket_(socket) {} -Exception WifiLanOutputStream::Write(const ByteArray& data) { +Exception WifiLanOutputStream::Write(absl::string_view data) { NSError* error = nil; BOOL result = [socket_ write:[NSData dataWithBytes:data.data() length:data.size()] error:&error]; if (!result) { diff --git a/internal/platform/implementation/shared/file.cc b/internal/platform/implementation/shared/file.cc index 5f1ea845..1c798269 100644 --- a/internal/platform/implementation/shared/file.cc +++ b/internal/platform/implementation/shared/file.cc @@ -85,7 +85,7 @@ Exception IOFile::Close() { return {Exception::kSuccess}; } -Exception IOFile::Write(const ByteArray& data) { +Exception IOFile::Write(absl::string_view data) { if (!file_.is_open()) { return {Exception::kIo}; } diff --git a/internal/platform/implementation/shared/file.h b/internal/platform/implementation/shared/file.h index fb3db59d..fbf7bfd0 100644 --- a/internal/platform/implementation/shared/file.h +++ b/internal/platform/implementation/shared/file.h @@ -43,7 +43,7 @@ class IOFile final : public api::InputFile, public api::OutputFile { std::int64_t GetTotalSize() const override { return total_size_; } Exception Close() override; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; absl::Time GetLastModifiedTime() const override; void SetLastModifiedTime(absl::Time last_modified_time) override; diff --git a/internal/platform/implementation/shared/file_test.cc b/internal/platform/implementation/shared/file_test.cc index c8597ddd..52c2cfbb 100644 --- a/internal/platform/implementation/shared/file_test.cc +++ b/internal/platform/implementation/shared/file_test.cc @@ -14,6 +14,7 @@ #include "internal/platform/implementation/shared/file.h" +#include #include #include #include @@ -22,6 +23,7 @@ #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" +#include "internal/platform/exception.h" namespace nearby { namespace shared { @@ -117,14 +119,14 @@ TEST_F(FileTest, IOFile_CloseInput) { TEST_F(FileTest, IOFile_NonExistentPathOutput) { auto io_file = shared::IOFile::CreateOutputFile("/not/a/valid/path.txt"); - ByteArray bytes("a", 1); + absl::string_view bytes("a", 1); EXPECT_TRUE(io_file->Write(bytes).Raised(Exception::kIo)); } TEST_F(FileTest, IOFile_Write) { auto io_file_output = shared::IOFile::CreateOutputFile(path_); - ByteArray bytes1("a"); - ByteArray bytes2("bc"); + absl::string_view bytes1("a"); + absl::string_view bytes2("bc"); EXPECT_EQ(io_file_output->Write(bytes1), Exception{Exception::kSuccess}); EXPECT_EQ(io_file_output->Write(bytes2), Exception{Exception::kSuccess}); auto io_file_input = @@ -135,7 +137,7 @@ TEST_F(FileTest, IOFile_Write) { TEST_F(FileTest, IOFile_CloseOutput) { auto io_file = shared::IOFile::CreateOutputFile(path_); io_file->Close(); - ByteArray bytes("a"); + absl::string_view bytes("a"); EXPECT_EQ(io_file->Write(bytes), Exception{Exception::kIo}); } diff --git a/internal/platform/implementation/windows/ble_socket.cc b/internal/platform/implementation/windows/ble_socket.cc index 587f2e11..fda672e3 100644 --- a/internal/platform/implementation/windows/ble_socket.cc +++ b/internal/platform/implementation/windows/ble_socket.cc @@ -16,10 +16,10 @@ #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/input_stream.h" -#include "internal/platform/logging.h" #include "internal/platform/output_stream.h" namespace nearby { @@ -32,38 +32,26 @@ OutputStream& BleSocket::GetOutputStream() { return output_stream_; } Exception BleSocket::Close() { return {Exception::kSuccess}; } bool BleSocket::Connect() { - // TODO(b/271031645): implement BLE socket using weave - VLOG(1) << __func__ << ": Connect to BLE peripheral"; return false; } ExceptionOr BleSocket::BleInputStream::Read(std::int64_t size) { - // TODO(b/271031645): implement BLE socket using weave - VLOG(1) << __func__ << ": Read data size=" << size; return ExceptionOr(Exception::kIo); } Exception BleSocket::BleInputStream::Close() { - // TODO(b/271031645): implement BLE socket using weave - VLOG(1) << __func__ << ": Close BLE input stream."; return {Exception::kSuccess}; } -Exception BleSocket::BleOutputStream::Write(const ByteArray& data) { - // TODO(b/271031645): implement BLE socket using weave - VLOG(1) << __func__ << ": Write data size=" << data.size(); +Exception BleSocket::BleOutputStream::Write(absl::string_view data) { return {Exception::kIo}; } Exception BleSocket::BleOutputStream::Flush() { - // TODO(b/271031645): implement BLE socket using weave - LOG(INFO) << __func__ << ": Flush is called."; return {Exception::kSuccess}; } Exception BleSocket::BleOutputStream::Close() { - // TODO(b/271031645): implement BLE socket using weave - LOG(INFO) << __func__ << ": close is called."; return {Exception::kSuccess}; } diff --git a/internal/platform/implementation/windows/ble_socket.h b/internal/platform/implementation/windows/ble_socket.h index 5397e5e1..4ab8080f 100644 --- a/internal/platform/implementation/windows/ble_socket.h +++ b/internal/platform/implementation/windows/ble_socket.h @@ -17,6 +17,7 @@ #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/implementation/ble.h" @@ -55,7 +56,7 @@ class BleSocket : public api::ble::BleSocket { public: ~BleOutputStream() override = default; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; }; diff --git a/internal/platform/implementation/windows/bluetooth_classic_socket.cc b/internal/platform/implementation/windows/bluetooth_classic_socket.cc index b2a41bb5..199f17b1 100644 --- a/internal/platform/implementation/windows/bluetooth_classic_socket.cc +++ b/internal/platform/implementation/windows/bluetooth_classic_socket.cc @@ -20,6 +20,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "internal/flags/nearby_flags.h" @@ -246,7 +247,8 @@ BluetoothSocket::BluetoothOutputStream::BluetoothOutputStream( winrt_output_stream_ = stream; } -Exception BluetoothSocket::BluetoothOutputStream::Write(const ByteArray& data) { +Exception BluetoothSocket::BluetoothOutputStream::Write( + absl::string_view data) { try { if (data.size() > write_buffer_.Capacity()) { LOG(WARNING) << __func__ diff --git a/internal/platform/implementation/windows/bluetooth_classic_socket.h b/internal/platform/implementation/windows/bluetooth_classic_socket.h index 026d162f..6c534f46 100644 --- a/internal/platform/implementation/windows/bluetooth_classic_socket.h +++ b/internal/platform/implementation/windows/bluetooth_classic_socket.h @@ -20,6 +20,7 @@ #include #include +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/implementation/bluetooth_classic.h" @@ -92,7 +93,7 @@ class BluetoothSocket : public api::BluetoothSocket { ::winrt::Windows::Storage::Streams::IOutputStream stream); ~BluetoothOutputStream() override = default; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; Exception Flush() override; Exception Close() override; diff --git a/internal/platform/implementation/windows/file.cc b/internal/platform/implementation/windows/file.cc index 7af1019c..e9076572 100644 --- a/internal/platform/implementation/windows/file.cc +++ b/internal/platform/implementation/windows/file.cc @@ -167,7 +167,7 @@ Exception IOFile::Close() { return {Exception::kSuccess}; } -Exception IOFile::Write(const ByteArray& data) { +Exception IOFile::Write(absl::string_view data) { if (file_ == INVALID_HANDLE_VALUE) { return {Exception::kIo}; } diff --git a/internal/platform/implementation/windows/file.h b/internal/platform/implementation/windows/file.h index 56b157e4..7d72804e 100644 --- a/internal/platform/implementation/windows/file.h +++ b/internal/platform/implementation/windows/file.h @@ -48,7 +48,7 @@ class IOFile final : public api::InputFile, public api::OutputFile { std::int64_t GetTotalSize() const override { return total_size_; } Exception Close() override; - Exception Write(const ByteArray& data) override; + Exception Write(absl::string_view data) override; absl::Time GetLastModifiedTime() const override; void SetLastModifiedTime(absl::Time last_modified_time) override; diff --git a/internal/platform/implementation/windows/file_test.cc b/internal/platform/implementation/windows/file_test.cc index e281e57b..40fe809c 100644 --- a/internal/platform/implementation/windows/file_test.cc +++ b/internal/platform/implementation/windows/file_test.cc @@ -161,7 +161,7 @@ TEST(IOFileTest, OutputFileAlreadyExists) { ASSERT_NE(output_file, nullptr); EXPECT_EQ(output_file->GetTotalSize(), 0); - ExceptionOr write_result = output_file->Write(ByteArray("test")); + ExceptionOr write_result = output_file->Write("test"); EXPECT_FALSE(write_result.ok()); EXPECT_TRUE(write_result.GetException().Raised(Exception::kIo)); @@ -173,9 +173,9 @@ TEST(IOFileTest, OutputFileWrite) { std::unique_ptr output_file = IOFile::CreateOutputFile(temp_file); ASSERT_NE(output_file, nullptr); - ExceptionOr write_result = output_file->Write(ByteArray("test1")); + ExceptionOr write_result = output_file->Write("test1"); EXPECT_TRUE(write_result.ok()); - write_result = output_file->Write(ByteArray("test2")); + write_result = output_file->Write("test2"); EXPECT_TRUE(write_result.ok()); EXPECT_TRUE(output_file->Close().Ok()); diff --git a/internal/platform/implementation/windows/nearby_client_socket.cc b/internal/platform/implementation/windows/nearby_client_socket.cc index c3eee84a..19b304b6 100644 --- a/internal/platform/implementation/windows/nearby_client_socket.cc +++ b/internal/platform/implementation/windows/nearby_client_socket.cc @@ -22,6 +22,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/time/time.h" #include "internal/flags/nearby_flags.h" #include "internal/platform/byte_array.h" @@ -217,7 +218,7 @@ ExceptionOr NearbyClientSocket::Skip(size_t offset) { return {Exception::kIo}; } -Exception NearbyClientSocket::Write(const ByteArray& data) { +Exception NearbyClientSocket::Write(absl::string_view data) { if (socket_ == INVALID_SOCKET) { LOG(WARNING) << "Trying to write to an invalid socket."; return {Exception::kIo}; diff --git a/internal/platform/implementation/windows/nearby_client_socket.h b/internal/platform/implementation/windows/nearby_client_socket.h index d7479fb0..001f7874 100644 --- a/internal/platform/implementation/windows/nearby_client_socket.h +++ b/internal/platform/implementation/windows/nearby_client_socket.h @@ -21,6 +21,7 @@ #include #include "absl/base/nullability.h" +#include "absl/strings/string_view.h" #include "absl/time/time.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" @@ -45,7 +46,7 @@ class NearbyClientSocket { bool Connect(const SocketAddress& server_address, absl::Duration timeout); ExceptionOr Read(std::int64_t size); ExceptionOr Skip(size_t offset); - Exception Write(const ByteArray& data); + Exception Write(absl::string_view data); Exception Flush(); Exception Close(); @@ -80,7 +81,7 @@ class SocketOutputStream : public OutputStream { : client_socket_(client_socket) {} ~SocketOutputStream() override = default; - Exception Write(const ByteArray& data) override { + Exception Write(absl::string_view data) override { return client_socket_->Write(data); } Exception Flush() override { return client_socket_->Flush(); } diff --git a/internal/platform/implementation/windows/nearby_client_socket_test.cc b/internal/platform/implementation/windows/nearby_client_socket_test.cc index eb3840f0..8dbdb202 100644 --- a/internal/platform/implementation/windows/nearby_client_socket_test.cc +++ b/internal/platform/implementation/windows/nearby_client_socket_test.cc @@ -132,7 +132,7 @@ TEST(NearbyClientSocketTest, Write) { /*addrlen=*/&peer_address_length); EXPECT_NE(accept_socket, INVALID_SOCKET); - EXPECT_TRUE(client_socket.Write(ByteArray("hello")).Ok()); + EXPECT_TRUE(client_socket.Write("hello").Ok()); std::string buffer; buffer.resize(5); EXPECT_EQ(recv(accept_socket, buffer.data(), 5, 0), 5); diff --git a/internal/platform/mock_output_stream.h b/internal/platform/mock_output_stream.h index cbcf16e8..ca6095de 100644 --- a/internal/platform/mock_output_stream.h +++ b/internal/platform/mock_output_stream.h @@ -16,7 +16,7 @@ #define THIRD_PARTY_NEARBY_INTERNAL_PLATFORM_MOCK_OUTPUT_STREAM_H_ #include "gmock/gmock.h" -#include "internal/platform/byte_array.h" +#include "absl/strings/string_view.h" #include "internal/platform/exception.h" #include "internal/platform/output_stream.h" @@ -24,7 +24,7 @@ namespace nearby { class MockOutputStream : public OutputStream { public: - MOCK_METHOD(Exception, Write, (const ByteArray& data), (override)); + MOCK_METHOD(Exception, Write, (absl::string_view data), (override)); MOCK_METHOD(Exception, Flush, (), (override)); MOCK_METHOD(Exception, Close, (), (override)); }; diff --git a/internal/platform/output_stream.h b/internal/platform/output_stream.h index 85310324..9feaccea 100644 --- a/internal/platform/output_stream.h +++ b/internal/platform/output_stream.h @@ -15,6 +15,8 @@ #ifndef PLATFORM_BASE_OUTPUT_STREAM_H_ #define PLATFORM_BASE_OUTPUT_STREAM_H_ +#include "absl/base/attributes.h" +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" @@ -27,9 +29,12 @@ class OutputStream { public: virtual ~OutputStream() = default; - virtual Exception Write(const ByteArray& data) = 0; // throws Exception::kIo + virtual Exception Write(absl::string_view data) = 0; // throws Exception::kIo virtual Exception Flush() = 0; // throws Exception::kIo virtual Exception Close() = 0; // throws Exception::kIo + + ABSL_DEPRECATED("Use the absl::string_view overload instead.") + Exception Write(const ByteArray& data) { return Write(data.AsStringView()); } }; } // namespace nearby diff --git a/internal/platform/pipe.cc b/internal/platform/pipe.cc index 9c6509a5..88983ff5 100644 --- a/internal/platform/pipe.cc +++ b/internal/platform/pipe.cc @@ -21,6 +21,7 @@ #include #include "absl/base/thread_annotations.h" +#include "absl/strings/string_view.h" #include "internal/platform/byte_array.h" #include "internal/platform/condition_variable.h" #include "internal/platform/exception.h" @@ -59,8 +60,8 @@ class Pipe { explicit PipeOutputStream(std::shared_ptr pipe) : pipe_(pipe) {} ~PipeOutputStream() override { DoClose(); } - Exception Write(const ByteArray& data) override { - return pipe_->Write(data); + Exception Write(absl::string_view data) override { + return pipe_->Write(ByteArray::FromStringView(data)); } Exception Flush() override { return {Exception::kSuccess}; } Exception Close() override { return DoClose(); } diff --git a/internal/platform/pipe_test.cc b/internal/platform/pipe_test.cc index 23ee4da0..3cae9d21 100644 --- a/internal/platform/pipe_test.cc +++ b/internal/platform/pipe_test.cc @@ -26,6 +26,8 @@ #include "gtest/gtest.h" #include "absl/strings/string_view.h" +#include "absl/time/clock.h" +#include "absl/time/time.h" #include "internal/platform/byte_array.h" #include "internal/platform/exception.h" #include "internal/platform/input_stream.h" @@ -46,19 +48,19 @@ TEST(PipeTest, ConstructorDestructorWorks) { TEST(PipeTest, SimpleWriteRead) { auto [input_stream, output_stream] = CreatePipe(); - std::string data("ABCD"); - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Ok()); + absl::string_view data("ABCD"); + EXPECT_TRUE(output_stream->Write(data).Ok()); ExceptionOr read_data = input_stream->Read(kChunkSize); EXPECT_TRUE(read_data.ok()); - EXPECT_EQ(data, std::string(read_data.result())); + EXPECT_EQ(data, read_data.result().AsStringView()); } TEST(PipeTest, WriteEndClosedBeforeRead) { auto [input_stream, output_stream] = CreatePipe(); - std::string data("ABCD"); - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Ok()); + absl::string_view data("ABCD"); + EXPECT_TRUE(output_stream->Write(data).Ok()); // Close the write end before the read end has even begun reading. EXPECT_TRUE(output_stream->Close().Ok()); @@ -66,7 +68,7 @@ TEST(PipeTest, WriteEndClosedBeforeRead) { // We should still be able to read what was written. ExceptionOr read_data = input_stream->Read(kChunkSize); EXPECT_TRUE(read_data.ok()); - EXPECT_EQ(data, std::string(read_data.result())); + EXPECT_EQ(data, read_data.result().AsStringView()); // And after that, we should get our indication that all the data that could // ever be read, has already been read. @@ -81,29 +83,29 @@ TEST(PipeTest, ReadEndClosedBeforeWrite) { // Close the read end before the write end has even begun writing. EXPECT_TRUE(input_stream->Close().Ok()); - std::string data("ABCD"); - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Raised(Exception::kIo)); + absl::string_view data("ABCD"); + EXPECT_TRUE(output_stream->Write(data).Raised(Exception::kIo)); } TEST(PipeTest, SizedReadMoreThanFirstChunkSize) { auto [input_stream, output_stream] = CreatePipe(); - std::string data("ABCD"); - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Ok()); + absl::string_view data("ABCD"); + EXPECT_TRUE(output_stream->Write(data).Ok()); // Even though we ask for double of what's there in the first chunk, we should // get back only what's there in that first chunk, and that's alright. ExceptionOr read_data = input_stream->Read(data.size() * 2); EXPECT_TRUE(read_data.ok()); - EXPECT_EQ(data, std::string(read_data.result())); + EXPECT_EQ(data, read_data.result().AsStringView()); } TEST(PipeTest, SizedReadLessThanFirstChunkSize) { auto [input_stream, output_stream] = CreatePipe(); std::string data_first_part("ABCD"); std::string data_second_part("EFGHIJ"); - std::string data = data_first_part + data_second_part; - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Ok()); + std::string combined_data = data_first_part + data_second_part; + EXPECT_TRUE(output_stream->Write(combined_data).Ok()); // When we ask for less than what's there in the first chunk, we should get // back exactly what we asked for, with the remainder still being available @@ -134,8 +136,8 @@ TEST(PipeTest, WriteAfterOutputStreamClosed) { output_stream->Close(); - std::string data("ABCD"); - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Raised(Exception::kIo)); + absl::string_view data("ABCD"); + EXPECT_TRUE(output_stream->Write(data).Raised(Exception::kIo)); } TEST(PipeTest, RepeatedClose) { @@ -216,7 +218,7 @@ TEST(PipeTest, ReadBlockedUntilWrite) { // State shared between this thread (the writer) and reader_thread. CrossThreadBool ok_for_read_to_unblock = false; - std::string data("ABCD"); + absl::string_view data("ABCD"); // Kick off reader_thread. Thread reader_thread; @@ -232,7 +234,7 @@ TEST(PipeTest, ReadBlockedUntilWrite) { ok_for_read_to_unblock = true; // Perform the actual write. - EXPECT_TRUE(output_stream->Write(ByteArray(data)).Ok()); + EXPECT_TRUE(output_stream->Write(data).Ok()); // And wait for reader_thread to finish. reader_thread.Join(); @@ -273,7 +275,7 @@ TEST(PipeTest, ConcurrentWriteAndRead) { void operator()() { for (auto& chunk : chunks_) { RandomSleep(); // Random pauses before each write. - EXPECT_TRUE(output_stream_->Write(ByteArray(chunk)).Ok()); + EXPECT_TRUE(output_stream_->Write(chunk).Ok()); } RandomSleep(); // A random pause before closing the writer end.