clang-format C++ examples (#25764)

pull/25779/head
Vijay Pai 4 years ago committed by GitHub
parent ec40f07ddb
commit ce16365421
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      examples/cpp/compression/greeter_client.cc
  2. 4
      examples/cpp/compression/greeter_server.cc
  3. 2
      examples/cpp/helloworld/cocoapods/HelloWorldCpp/AppDelegate.h
  4. 1
      examples/cpp/helloworld/cocoapods/HelloWorldCpp/ViewController.h
  5. 17
      examples/cpp/helloworld/cocoapods/HelloWorldCpp/ViewController.mm
  6. 4
      examples/cpp/helloworld/cocoapods/HelloWorldCpp/main.m
  7. 6
      examples/cpp/helloworld/greeter_async_client.cc
  8. 182
      examples/cpp/helloworld/greeter_async_client2.cc
  9. 10
      examples/cpp/helloworld/greeter_async_server.cc
  10. 11
      examples/cpp/helloworld/greeter_client.cc
  11. 6
      examples/cpp/helloworld/greeter_server.cc
  12. 4
      examples/cpp/load_balancing/greeter_client.cc
  13. 4
      examples/cpp/load_balancing/greeter_server.cc
  14. 21
      examples/cpp/metadata/greeter_client.cc
  15. 17
      examples/cpp/metadata/greeter_server.cc
  16. 1
      examples/cpp/route_guide/helper.h
  17. 61
      examples/cpp/route_guide/route_guide_client.cc
  18. 32
      examples/cpp/route_guide/route_guide_server.cc
  19. 2
      tools/dockerfile/grpc_clang_format/clang_format_all_the_things.sh

@ -32,9 +32,9 @@ using grpc::Channel;
using grpc::ChannelArguments; using grpc::ChannelArguments;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class GreeterClient { class GreeterClient {
public: public:

@ -32,9 +32,9 @@ using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
using grpc::ServerContext; using grpc::ServerContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
// Logic and data behind the server's behavior. // Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service { class GreeterServiceImpl final : public Greeter::Service {

@ -19,5 +19,5 @@
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate> @interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window; @property(strong, nonatomic) UIWindow *window;
@end @end

@ -20,4 +20,3 @@
@interface ViewController : UIViewController @interface ViewController : UIViewController
@end @end

@ -18,14 +18,15 @@
#import "ViewController.h" #import "ViewController.h"
#import <grpcpp/grpcpp.h> #import <grpcpp/grpcpp.h>
#include <grpcpp/generic/generic_stub.h>
#include <grpcpp/generic/async_generic_service.h> #include <grpcpp/generic/async_generic_service.h>
#include <grpcpp/generic/generic_stub.h>
static void* tag(int i) { return (void*)(intptr_t)i; } static void* tag(int i) { return (void*)(intptr_t)i; }
// Serialized Proto bytes of Hello World example // Serialized Proto bytes of Hello World example
const uint8_t kMessage[] = const uint8_t kMessage[] = {0x0A, 0x0B, 0x4F, 0x62, 0x6A, 0x65, 0x63,
{0x0A, 0x0B, 0x4F, 0x62, 0x6A, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x2D, 0x43}; 0x74, 0x69, 0x76, 0x65, 0x2D, 0x43};
@interface ViewController () @interface ViewController ()
@ -57,7 +58,7 @@ const uint8_t kMessage[] =
abort(); abort();
} }
grpc::Slice send_slice = grpc::Slice(kMessage, sizeof(kMessage) / sizeof(kMessage[0])); grpc::Slice send_slice = grpc::Slice(kMessage, sizeof(kMessage) / sizeof(kMessage[0]));
std::unique_ptr<grpc::ByteBuffer> send_buffer(new grpc::ByteBuffer(&send_slice, 1)); std::unique_ptr<grpc::ByteBuffer> send_buffer(new grpc::ByteBuffer(&send_slice, 1));
call->Write(*send_buffer, tag(2)); call->Write(*send_buffer, tag(2));
cq_.Next(&got_tag, &ok); cq_.Next(&got_tag, &ok);
if (!ok || got_tag != tag(2)) { if (!ok || got_tag != tag(2)) {
@ -85,17 +86,17 @@ const uint8_t kMessage[] =
} }
std::vector<grpc::Slice> slices; std::vector<grpc::Slice> slices;
recv_buffer.Dump(&slices); recv_buffer.Dump(&slices);
NSString *recvBytes = [[NSString alloc] init]; NSString* recvBytes = [[NSString alloc] init];
for (auto slice : slices) { for (auto slice : slices) {
auto p = slice.begin(); auto p = slice.begin();
while (p != slice.end()) { while (p != slice.end()) {
recvBytes = recvBytes = [recvBytes stringByAppendingString:[NSString stringWithFormat:@"%02x ", *p]];
[recvBytes stringByAppendingString:[NSString stringWithFormat:@"%02x ", *p]];
p++; p++;
} }
} }
NSLog(@"Hello World succeeded.\nReceived bytes: %@\n" NSLog(@"Hello World succeeded.\nReceived bytes: %@\n"
"Expected bytes: 0a 11 48 65 6c 6c 6f 20 4f 62 6a 65 63 74 69 76 65 2d 43", recvBytes); "Expected bytes: 0a 11 48 65 6c 6c 6f 20 4f 62 6a 65 63 74 69 76 65 2d 43",
recvBytes);
} }
@end @end

@ -19,8 +19,8 @@
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#import "AppDelegate.h" #import "AppDelegate.h"
int main(int argc, char * argv[]) { int main(int argc, char* argv[]) {
@autoreleasepool { @autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
} }
} }

@ -20,8 +20,8 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/grpcpp.h>
#ifdef BAZEL_BUILD #ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h" #include "examples/protos/helloworld.grpc.pb.h"
@ -34,9 +34,9 @@ using grpc::ClientAsyncResponseReader;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::CompletionQueue; using grpc::CompletionQueue;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class GreeterClient { class GreeterClient {
public: public:

@ -20,8 +20,8 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/grpcpp.h>
#include <thread> #include <thread>
#ifdef BAZEL_BUILD #ifdef BAZEL_BUILD
@ -35,113 +35,109 @@ using grpc::ClientAsyncResponseReader;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::CompletionQueue; using grpc::CompletionQueue;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class GreeterClient { class GreeterClient {
public: public:
explicit GreeterClient(std::shared_ptr<Channel> channel) explicit GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {} : stub_(Greeter::NewStub(channel)) {}
// Assembles the client's payload and sends it to the server. // Assembles the client's payload and sends it to the server.
void SayHello(const std::string& user) { void SayHello(const std::string& user) {
// Data we are sending to the server. // Data we are sending to the server.
HelloRequest request; HelloRequest request;
request.set_name(user); request.set_name(user);
// Call object to store rpc data // Call object to store rpc data
AsyncClientCall* call = new AsyncClientCall; AsyncClientCall* call = new AsyncClientCall;
// stub_->PrepareAsyncSayHello() creates an RPC object, returning // stub_->PrepareAsyncSayHello() creates an RPC object, returning
// an instance to store in "call" but does not actually start the RPC // an instance to store in "call" but does not actually start the RPC
// Because we are using the asynchronous API, we need to hold on to // Because we are using the asynchronous API, we need to hold on to
// the "call" instance in order to get updates on the ongoing RPC. // the "call" instance in order to get updates on the ongoing RPC.
call->response_reader = call->response_reader =
stub_->PrepareAsyncSayHello(&call->context, request, &cq_); stub_->PrepareAsyncSayHello(&call->context, request, &cq_);
// StartCall initiates the RPC call // StartCall initiates the RPC call
call->response_reader->StartCall(); call->response_reader->StartCall();
// Request that, upon completion of the RPC, "reply" be updated with the // Request that, upon completion of the RPC, "reply" be updated with the
// server's response; "status" with the indication of whether the operation // server's response; "status" with the indication of whether the operation
// was successful. Tag the request with the memory address of the call object. // was successful. Tag the request with the memory address of the call
call->response_reader->Finish(&call->reply, &call->status, (void*)call); // object.
call->response_reader->Finish(&call->reply, &call->status, (void*)call);
}
// Loop while listening for completed responses.
// Prints out the response from the server.
void AsyncCompleteRpc() {
void* got_tag;
bool ok = false;
// Block until the next result is available in the completion queue "cq".
while (cq_.Next(&got_tag, &ok)) {
// The tag in this example is the memory location of the call object
AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
// Verify that the request was completed successfully. Note that "ok"
// corresponds solely to the request for updates introduced by Finish().
GPR_ASSERT(ok);
if (call->status.ok())
std::cout << "Greeter received: " << call->reply.message() << std::endl;
else
std::cout << "RPC failed" << std::endl;
// Once we're complete, deallocate the call object.
delete call;
} }
}
// Loop while listening for completed responses. private:
// Prints out the response from the server. // struct for keeping state and data information
void AsyncCompleteRpc() { struct AsyncClientCall {
void* got_tag; // Container for the data we expect from the server.
bool ok = false; HelloReply reply;
// Block until the next result is available in the completion queue "cq".
while (cq_.Next(&got_tag, &ok)) {
// The tag in this example is the memory location of the call object
AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
// Verify that the request was completed successfully. Note that "ok"
// corresponds solely to the request for updates introduced by Finish().
GPR_ASSERT(ok);
if (call->status.ok())
std::cout << "Greeter received: " << call->reply.message() << std::endl;
else
std::cout << "RPC failed" << std::endl;
// Once we're complete, deallocate the call object.
delete call;
}
}
private:
// struct for keeping state and data information
struct AsyncClientCall {
// Container for the data we expect from the server.
HelloReply reply;
// Context for the client. It could be used to convey extra information to
// the server and/or tweak certain RPC behaviors.
ClientContext context;
// Storage for the status of the RPC upon completion. // Context for the client. It could be used to convey extra information to
Status status; // the server and/or tweak certain RPC behaviors.
ClientContext context;
// Storage for the status of the RPC upon completion.
Status status;
std::unique_ptr<ClientAsyncResponseReader<HelloReply>> response_reader; std::unique_ptr<ClientAsyncResponseReader<HelloReply>> response_reader;
}; };
// Out of the passed in Channel comes the stub, stored here, our view of the // Out of the passed in Channel comes the stub, stored here, our view of the
// server's exposed services. // server's exposed services.
std::unique_ptr<Greeter::Stub> stub_; std::unique_ptr<Greeter::Stub> stub_;
// The producer-consumer queue we use to communicate asynchronously with the // The producer-consumer queue we use to communicate asynchronously with the
// gRPC runtime. // gRPC runtime.
CompletionQueue cq_; CompletionQueue cq_;
}; };
int main(int argc, char** argv) { int main(int argc, char** argv) {
// Instantiate the client. It requires a channel, out of which the actual RPCs
// are created. This channel models a connection to an endpoint (in this case,
// localhost at port 50051). We indicate that the channel isn't authenticated
// (use of InsecureChannelCredentials()).
GreeterClient greeter(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
// Spawn reader thread that loops indefinitely
std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);
// Instantiate the client. It requires a channel, out of which the actual RPCs for (int i = 0; i < 100; i++) {
// are created. This channel models a connection to an endpoint (in this case, std::string user("world " + std::to_string(i));
// localhost at port 50051). We indicate that the channel isn't authenticated greeter.SayHello(user); // The actual RPC call!
// (use of InsecureChannelCredentials()). }
GreeterClient greeter(grpc::CreateChannel(
"localhost:50051", grpc::InsecureChannelCredentials()));
// Spawn reader thread that loops indefinitely
std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);
for (int i = 0; i < 100; i++) {
std::string user("world " + std::to_string(i));
greeter.SayHello(user); // The actual RPC call!
}
std::cout << "Press control-c to quit" << std::endl << std::endl; std::cout << "Press control-c to quit" << std::endl << std::endl;
thread_.join(); //blocks forever thread_.join(); // blocks forever
return 0; return 0;
} }

@ -16,13 +16,13 @@
* *
*/ */
#include <memory>
#include <iostream> #include <iostream>
#include <memory>
#include <string> #include <string>
#include <thread> #include <thread>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/grpcpp.h>
#ifdef BAZEL_BUILD #ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h" #include "examples/protos/helloworld.grpc.pb.h"
@ -33,12 +33,12 @@
using grpc::Server; using grpc::Server;
using grpc::ServerAsyncResponseWriter; using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder; using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCompletionQueue; using grpc::ServerCompletionQueue;
using grpc::ServerContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class ServerImpl final { class ServerImpl final {
public: public:

@ -31,9 +31,9 @@
using grpc::Channel; using grpc::Channel;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class GreeterClient { class GreeterClient {
public: public:
@ -87,7 +87,8 @@ int main(int argc, char** argv) {
if (arg_val[start_pos] == '=') { if (arg_val[start_pos] == '=') {
target_str = arg_val.substr(start_pos + 1); target_str = arg_val.substr(start_pos + 1);
} else { } else {
std::cout << "The only correct argument syntax is --target=" << std::endl; std::cout << "The only correct argument syntax is --target="
<< std::endl;
return 0; return 0;
} }
} else { } else {
@ -97,8 +98,8 @@ int main(int argc, char** argv) {
} else { } else {
target_str = "localhost:50051"; target_str = "localhost:50051";
} }
GreeterClient greeter(grpc::CreateChannel( GreeterClient greeter(
target_str, grpc::InsecureChannelCredentials())); grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
std::string user("world"); std::string user("world");
std::string reply = greeter.SayHello(user); std::string reply = greeter.SayHello(user);
std::cout << "Greeter received: " << reply << std::endl; std::cout << "Greeter received: " << reply << std::endl;

@ -20,9 +20,9 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h> #include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h> #include <grpcpp/health_check_service_interface.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#ifdef BAZEL_BUILD #ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h" #include "examples/protos/helloworld.grpc.pb.h"
@ -34,9 +34,9 @@ using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
using grpc::ServerContext; using grpc::ServerContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
// Logic and data behind the server's behavior. // Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service { class GreeterServiceImpl final : public Greeter::Service {

@ -32,9 +32,9 @@ using grpc::Channel;
using grpc::ChannelArguments; using grpc::ChannelArguments;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class GreeterClient { class GreeterClient {
public: public:

@ -32,9 +32,9 @@ using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
using grpc::ServerContext; using grpc::ServerContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
// Logic and data behind the server's behavior. // Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service { class GreeterServiceImpl final : public Greeter::Service {

@ -31,9 +31,9 @@
using grpc::Channel; using grpc::Channel;
using grpc::ClientContext; using grpc::ClientContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
class CustomHeaderClient { class CustomHeaderClient {
public: public:
@ -57,9 +57,8 @@ class CustomHeaderClient {
// Setting custom metadata to be sent to the server // Setting custom metadata to be sent to the server
context.AddMetadata("custom-header", "Custom Value"); context.AddMetadata("custom-header", "Custom Value");
// Setting custom binary metadata // Setting custom binary metadata
char bytes[8] = {'\0', '\1', '\2', '\3', char bytes[8] = {'\0', '\1', '\2', '\3', '\4', '\5', '\6', '\7'};
'\4', '\5', '\6', '\7'};
context.AddMetadata("custom-bin", std::string(bytes, 8)); context.AddMetadata("custom-bin", std::string(bytes, 8));
// The actual RPC. // The actual RPC.
@ -67,8 +66,16 @@ class CustomHeaderClient {
// Act upon its status. // Act upon its status.
if (status.ok()) { if (status.ok()) {
std::cout << "Client received initial metadata from server: " << context.GetServerInitialMetadata().find("custom-server-metadata")->second << std::endl; std::cout << "Client received initial metadata from server: "
std::cout << "Client received trailing metadata from server: " << context.GetServerTrailingMetadata().find("custom-trailing-metadata")->second << std::endl; << context.GetServerInitialMetadata()
.find("custom-server-metadata")
->second
<< std::endl;
std::cout << "Client received trailing metadata from server: "
<< context.GetServerTrailingMetadata()
.find("custom-trailing-metadata")
->second
<< std::endl;
return reply.message(); return reply.message();
} else { } else {
std::cout << status.error_code() << ": " << status.error_message() std::cout << status.error_code() << ": " << status.error_message()

@ -32,9 +32,9 @@ using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
using grpc::ServerContext; using grpc::ServerContext;
using grpc::Status; using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter; using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;
// Logic and data behind the server's behavior. // Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service { class GreeterServiceImpl final : public Greeter::Service {
@ -44,25 +44,28 @@ class GreeterServiceImpl final : public Greeter::Service {
// Get the client's initial metadata // Get the client's initial metadata
std::cout << "Client metadata: " << std::endl; std::cout << "Client metadata: " << std::endl;
const std::multimap<grpc::string_ref, grpc::string_ref> metadata = context->client_metadata(); const std::multimap<grpc::string_ref, grpc::string_ref> metadata =
context->client_metadata();
for (auto iter = metadata.begin(); iter != metadata.end(); ++iter) { for (auto iter = metadata.begin(); iter != metadata.end(); ++iter) {
std::cout << "Header key: " << iter->first << ", value: "; std::cout << "Header key: " << iter->first << ", value: ";
// Check for binary value // Check for binary value
size_t isbin = iter->first.find("-bin"); size_t isbin = iter->first.find("-bin");
if ((isbin != std::string::npos) && (isbin + 4 == iter->first.size())) { if ((isbin != std::string::npos) && (isbin + 4 == iter->first.size())) {
std::cout << std::hex; std::cout << std::hex;
for (auto c : iter->second) { for (auto c : iter->second) {
std::cout << static_cast<unsigned int>(c); std::cout << static_cast<unsigned int>(c);
} }
std::cout << std::dec; std::cout << std::dec;
} else { } else {
std::cout << iter->second; std::cout << iter->second;
} }
std::cout << std::endl; std::cout << std::endl;
} }
context->AddInitialMetadata("custom-server-metadata", "initial metadata value"); context->AddInitialMetadata("custom-server-metadata",
context->AddTrailingMetadata("custom-trailing-metadata", "trailing metadata value"); "initial metadata value");
context->AddTrailingMetadata("custom-trailing-metadata",
"trailing metadata value");
reply->set_message(prefix + request->name()); reply->set_message(prefix + request->name());
return Status::OK; return Status::OK;
} }

@ -32,4 +32,3 @@ void ParseDb(const std::string& db, std::vector<Feature>* feature_list);
} // namespace routeguide } // namespace routeguide
#endif // GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_ #endif // GRPC_COMMON_CPP_ROUTE_GUIDE_HELPER_H_

@ -41,12 +41,12 @@ using grpc::ClientReader;
using grpc::ClientReaderWriter; using grpc::ClientReaderWriter;
using grpc::ClientWriter; using grpc::ClientWriter;
using grpc::Status; using grpc::Status;
using routeguide::Point;
using routeguide::Feature; using routeguide::Feature;
using routeguide::Point;
using routeguide::Rectangle; using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide; using routeguide::RouteGuide;
using routeguide::RouteNote;
using routeguide::RouteSummary;
Point MakePoint(long latitude, long longitude) { Point MakePoint(long latitude, long longitude) {
Point p; Point p;
@ -55,16 +55,15 @@ Point MakePoint(long latitude, long longitude) {
return p; return p;
} }
Feature MakeFeature(const std::string& name, Feature MakeFeature(const std::string& name, long latitude, long longitude) {
long latitude, long longitude) {
Feature f; Feature f;
f.set_name(name); f.set_name(name);
f.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
return f; return f;
} }
RouteNote MakeRouteNote(const std::string& message, RouteNote MakeRouteNote(const std::string& message, long latitude,
long latitude, long longitude) { long longitude) {
RouteNote n; RouteNote n;
n.set_message(message); n.set_message(message);
n.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
@ -102,10 +101,9 @@ class RouteGuideClient {
std::unique_ptr<ClientReader<Feature> > reader( std::unique_ptr<ClientReader<Feature> > reader(
stub_->ListFeatures(&context, rect)); stub_->ListFeatures(&context, rect));
while (reader->Read(&feature)) { while (reader->Read(&feature)) {
std::cout << "Found feature called " std::cout << "Found feature called " << feature.name() << " at "
<< feature.name() << " at " << feature.location().latitude() / kCoordFactor_ << ", "
<< feature.location().latitude()/kCoordFactor_ << ", " << feature.location().longitude() / kCoordFactor_ << std::endl;
<< feature.location().longitude()/kCoordFactor_ << std::endl;
} }
Status status = reader->Finish(); Status status = reader->Finish();
if (status.ok()) { if (status.ok()) {
@ -125,22 +123,21 @@ class RouteGuideClient {
std::default_random_engine generator(seed); std::default_random_engine generator(seed);
std::uniform_int_distribution<int> feature_distribution( std::uniform_int_distribution<int> feature_distribution(
0, feature_list_.size() - 1); 0, feature_list_.size() - 1);
std::uniform_int_distribution<int> delay_distribution( std::uniform_int_distribution<int> delay_distribution(500, 1500);
500, 1500);
std::unique_ptr<ClientWriter<Point> > writer( std::unique_ptr<ClientWriter<Point> > writer(
stub_->RecordRoute(&context, &stats)); stub_->RecordRoute(&context, &stats));
for (int i = 0; i < kPoints; i++) { for (int i = 0; i < kPoints; i++) {
const Feature& f = feature_list_[feature_distribution(generator)]; const Feature& f = feature_list_[feature_distribution(generator)];
std::cout << "Visiting point " std::cout << "Visiting point " << f.location().latitude() / kCoordFactor_
<< f.location().latitude()/kCoordFactor_ << ", " << ", " << f.location().longitude() / kCoordFactor_
<< f.location().longitude()/kCoordFactor_ << std::endl; << std::endl;
if (!writer->Write(f.location())) { if (!writer->Write(f.location())) {
// Broken stream. // Broken stream.
break; break;
} }
std::this_thread::sleep_for(std::chrono::milliseconds( std::this_thread::sleep_for(
delay_distribution(generator))); std::chrono::milliseconds(delay_distribution(generator)));
} }
writer->WritesDone(); writer->WritesDone();
Status status = writer->Finish(); Status status = writer->Finish();
@ -162,14 +159,13 @@ class RouteGuideClient {
stub_->RouteChat(&context)); stub_->RouteChat(&context));
std::thread writer([stream]() { std::thread writer([stream]() {
std::vector<RouteNote> notes{ std::vector<RouteNote> notes{MakeRouteNote("First message", 0, 0),
MakeRouteNote("First message", 0, 0), MakeRouteNote("Second message", 0, 1),
MakeRouteNote("Second message", 0, 1), MakeRouteNote("Third message", 1, 0),
MakeRouteNote("Third message", 1, 0), MakeRouteNote("Fourth message", 0, 0)};
MakeRouteNote("Fourth message", 0, 0)};
for (const RouteNote& note : notes) { for (const RouteNote& note : notes) {
std::cout << "Sending message " << note.message() std::cout << "Sending message " << note.message() << " at "
<< " at " << note.location().latitude() << ", " << note.location().latitude() << ", "
<< note.location().longitude() << std::endl; << note.location().longitude() << std::endl;
stream->Write(note); stream->Write(note);
} }
@ -178,8 +174,8 @@ class RouteGuideClient {
RouteNote server_note; RouteNote server_note;
while (stream->Read(&server_note)) { while (stream->Read(&server_note)) {
std::cout << "Got message " << server_note.message() std::cout << "Got message " << server_note.message() << " at "
<< " at " << server_note.location().latitude() << ", " << server_note.location().latitude() << ", "
<< server_note.location().longitude() << std::endl; << server_note.location().longitude() << std::endl;
} }
writer.join(); writer.join();
@ -190,7 +186,6 @@ class RouteGuideClient {
} }
private: private:
bool GetOneFeature(const Point& point, Feature* feature) { bool GetOneFeature(const Point& point, Feature* feature) {
ClientContext context; ClientContext context;
Status status = stub_->GetFeature(&context, point, feature); Status status = stub_->GetFeature(&context, point, feature);
@ -204,12 +199,12 @@ class RouteGuideClient {
} }
if (feature->name().empty()) { if (feature->name().empty()) {
std::cout << "Found no feature at " std::cout << "Found no feature at "
<< feature->location().latitude()/kCoordFactor_ << ", " << feature->location().latitude() / kCoordFactor_ << ", "
<< feature->location().longitude()/kCoordFactor_ << std::endl; << feature->location().longitude() / kCoordFactor_ << std::endl;
} else { } else {
std::cout << "Found feature called " << feature->name() << " at " std::cout << "Found feature called " << feature->name() << " at "
<< feature->location().latitude()/kCoordFactor_ << ", " << feature->location().latitude() / kCoordFactor_ << ", "
<< feature->location().longitude()/kCoordFactor_ << std::endl; << feature->location().longitude() / kCoordFactor_ << std::endl;
} }
return true; return true;
} }

@ -24,10 +24,10 @@
#include <string> #include <string>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h> #include <grpcpp/server.h>
#include <grpcpp/server_builder.h> #include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h> #include <grpcpp/server_context.h>
#include <grpcpp/security/server_credentials.h>
#include "helper.h" #include "helper.h"
#ifdef BAZEL_BUILD #ifdef BAZEL_BUILD
#include "examples/protos/route_guide.grpc.pb.h" #include "examples/protos/route_guide.grpc.pb.h"
@ -42,18 +42,15 @@ using grpc::ServerReader;
using grpc::ServerReaderWriter; using grpc::ServerReaderWriter;
using grpc::ServerWriter; using grpc::ServerWriter;
using grpc::Status; using grpc::Status;
using routeguide::Point;
using routeguide::Feature; using routeguide::Feature;
using routeguide::Point;
using routeguide::Rectangle; using routeguide::Rectangle;
using routeguide::RouteSummary;
using routeguide::RouteNote;
using routeguide::RouteGuide; using routeguide::RouteGuide;
using routeguide::RouteNote;
using routeguide::RouteSummary;
using std::chrono::system_clock; using std::chrono::system_clock;
float ConvertToRadians(float num) { return num * 3.1415926 / 180; }
float ConvertToRadians(float num) {
return num * 3.1415926 /180;
}
// The formula is based on http://mathforum.org/library/drmath/view/51879.html // The formula is based on http://mathforum.org/library/drmath/view/51879.html
float GetDistance(const Point& start, const Point& end) { float GetDistance(const Point& start, const Point& end) {
@ -64,13 +61,13 @@ float GetDistance(const Point& start, const Point& end) {
float lon_2 = end.longitude() / kCoordFactor; float lon_2 = end.longitude() / kCoordFactor;
float lat_rad_1 = ConvertToRadians(lat_1); float lat_rad_1 = ConvertToRadians(lat_1);
float lat_rad_2 = ConvertToRadians(lat_2); float lat_rad_2 = ConvertToRadians(lat_2);
float delta_lat_rad = ConvertToRadians(lat_2-lat_1); float delta_lat_rad = ConvertToRadians(lat_2 - lat_1);
float delta_lon_rad = ConvertToRadians(lon_2-lon_1); float delta_lon_rad = ConvertToRadians(lon_2 - lon_1);
float a = pow(sin(delta_lat_rad/2), 2) + cos(lat_rad_1) * cos(lat_rad_2) * float a = pow(sin(delta_lat_rad / 2), 2) +
pow(sin(delta_lon_rad/2), 2); cos(lat_rad_1) * cos(lat_rad_2) * pow(sin(delta_lon_rad / 2), 2);
float c = 2 * atan2(sqrt(a), sqrt(1-a)); float c = 2 * atan2(sqrt(a), sqrt(1 - a));
int R = 6371000; // metres int R = 6371000; // metres
return R * c; return R * c;
} }
@ -111,8 +108,7 @@ class RouteGuideImpl final : public RouteGuide::Service {
for (const Feature& f : feature_list_) { for (const Feature& f : feature_list_) {
if (f.location().longitude() >= left && if (f.location().longitude() >= left &&
f.location().longitude() <= right && f.location().longitude() <= right &&
f.location().latitude() >= bottom && f.location().latitude() >= bottom && f.location().latitude() <= top) {
f.location().latitude() <= top) {
writer->Write(f); writer->Write(f);
} }
} }
@ -142,8 +138,8 @@ class RouteGuideImpl final : public RouteGuide::Service {
summary->set_point_count(point_count); summary->set_point_count(point_count);
summary->set_feature_count(feature_count); summary->set_feature_count(feature_count);
summary->set_distance(static_cast<long>(distance)); summary->set_distance(static_cast<long>(distance));
auto secs = std::chrono::duration_cast<std::chrono::seconds>( auto secs =
end_time - start_time); std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
summary->set_elapsed_time(secs.count()); summary->set_elapsed_time(secs.count());
return Status::OK; return Status::OK;

@ -16,7 +16,7 @@
set -e set -e
# directories to run against # directories to run against
DIRS="src/core/lib src/core/tsi src/core/ext src/cpp test/core test/cpp include src/compiler src/csharp src/ruby third_party/address_sorting src/objective-c tools/distrib/python" DIRS="examples/cpp src/core/lib src/core/tsi src/core/ext src/cpp test/core test/cpp include src/compiler src/csharp src/ruby third_party/address_sorting src/objective-c tools/distrib/python"
# file matching patterns to check # file matching patterns to check
GLOB="*.h *.c *.cc *.m *.mm" GLOB="*.h *.c *.cc *.m *.mm"

Loading…
Cancel
Save