scoped_service_publisher.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_FUCHSIA_SCOPED_SERVICE_PUBLISHER_H_
  5. #define BASE_FUCHSIA_SCOPED_SERVICE_PUBLISHER_H_
  6. #include <memory>
  7. #include <string>
  8. #include <utility>
  9. #include <lib/async/dispatcher.h>
  10. #include <lib/fidl/cpp/interface_request.h>
  11. #include <lib/sys/cpp/outgoing_directory.h>
  12. #include <lib/vfs/cpp/pseudo_dir.h>
  13. #include <lib/vfs/cpp/service.h>
  14. #include <lib/zx/channel.h>
  15. #include "base/base_export.h"
  16. #include "base/fuchsia/fuchsia_logging.h"
  17. #include "base/strings/string_piece.h"
  18. namespace base {
  19. template <typename Interface>
  20. class BASE_EXPORT ScopedServicePublisher {
  21. public:
  22. // Publishes a public service in the specified |outgoing_directory|.
  23. // |outgoing_directory| and |handler| must outlive the binding.
  24. ScopedServicePublisher(sys::OutgoingDirectory* outgoing_directory,
  25. fidl::InterfaceRequestHandler<Interface> handler,
  26. base::StringPiece name = Interface::Name_)
  27. : ScopedServicePublisher(outgoing_directory->GetOrCreateDirectory("svc"),
  28. std::move(handler), name) {}
  29. // Publishes a service in the specified |pseudo_dir|. |pseudo_dir| and
  30. // |handler| must outlive the binding.
  31. ScopedServicePublisher(vfs::PseudoDir* pseudo_dir,
  32. fidl::InterfaceRequestHandler<Interface> handler,
  33. base::StringPiece name = Interface::Name_)
  34. : pseudo_dir_(pseudo_dir), name_(name) {
  35. zx_status_t status = pseudo_dir_->AddEntry(
  36. name_, std::make_unique<vfs::Service>(std::move(handler)));
  37. ZX_DCHECK(status == ZX_OK, status) << "vfs::PseudoDir::AddEntry";
  38. }
  39. ScopedServicePublisher(const ScopedServicePublisher&) = delete;
  40. ScopedServicePublisher& operator=(const ScopedServicePublisher&) = delete;
  41. ~ScopedServicePublisher() { pseudo_dir_->RemoveEntry(name_); }
  42. private:
  43. vfs::PseudoDir* const pseudo_dir_ = nullptr;
  44. std::string name_;
  45. };
  46. } // namespace base
  47. #endif // BASE_FUCHSIA_SCOPED_SERVICE_PUBLISHER_H_