### Example Usage: Binding and Serving with Incoming Stream Source: https://docs.rs/tonic/latest/src/tonic/transport/server/incoming.rs.html Demonstrates how to bind a `TcpIncoming` to a free port and then use it with `Server::serve_with_incoming` to serve a gRPC service. This example finds an available port dynamically. ```rust # use tower_service::Service; # use http::{request::Request, response::Response}; # use tonic::{body::Body, server::NamedService, transport::{Server, server::TcpIncoming}}; # use core::convert::Infallible; # use std::error::Error; # fn main() { } // Cannot have type parameters, hence instead define: # fn run(some_service: S) -> Result<(), Box> # where # S: Service, Response = Response, Error = Infallible> + NamedService + Clone + Send + Sync + 'static, # S::Future: Send + 'static, # { # // Find a free port # let mut port = 1322; # let tinc = loop { # let addr = format!( ``` -------------------------------- ### Get All Binary Metadata Values Source: https://docs.rs/tonic/latest/src/tonic/metadata/map.rs.html Illustrates retrieving all binary values for a given key. Includes examples of successful retrieval and failure cases for wrong types or invalid key formats. ```rust /// # use tonic::metadata::* /// let mut map = MetadataMap::new(); /// /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello")); /// map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"goodbye")); /// /// { /// let view = map.get_all_bin("trace-proto-bin"); /// /// let mut iter = view.iter(); /// assert_eq!(&"hello", iter.next().unwrap()); /// assert_eq!(&"goodbye", iter.next().unwrap()); /// assert!(iter.next().is_none()); /// } /// /// // Attempting to read a key of the wrong type fails by not /// // finding anything. /// map.append("host", "world".parse().unwrap()); /// assert!(map.get_all_bin("host").iter().next().is_none()); /// assert!(map.get_all_bin("host".to_string()).iter().next().is_none()); /// assert!(map.get_all_bin(&("host".to_string())).iter().next().is_none()); /// /// // Attempting to read an invalid key string fails by not /// // finding anything. /// assert!(map.get_all_bin("host{}-bin").iter().next().is_none()); /// assert!(map.get_all_bin("host{}-bin".to_string()).iter().next().is_none()); /// assert!(map.get_all_bin(&("host{}-bin".to_string())).iter().next().is_none()); ``` -------------------------------- ### StreamingService Implementation Example Source: https://docs.rs/tonic/latest/tonic/server/trait.StreamingService.html Example of how `StreamingService` is implemented for types that already implement `tower_service::Service` with compatible streaming capabilities. ```APIDOC ### Implementors #### impl StreamingService for T where T: Service>, Response = Response, Error = Status>, S: Stream>, ##### type Response = M2 ##### type ResponseStream = S ##### type Future = >>>::Future ``` -------------------------------- ### Initialize RoutesBuilder Source: https://docs.rs/tonic/latest/src/tonic/service/router.rs.html Create a new `RoutesBuilder` to start adding services. ```rust let mut builder = RoutesBuilder::default(); ``` -------------------------------- ### Example: Get Endpoint URI Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/endpoint.rs.html Demonstrates how to retrieve the URI of a Tonic endpoint. Assumes an endpoint is already created. ```rust let endpoint = Endpoint::from_static("https://example.com"); assert_eq!(endpoint.uri(), &Uri::from_static("https://example.com")); ``` -------------------------------- ### Panic on Overflow Example Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html This example demonstrates a panic that occurs at runtime when attempting to repeat a byte string beyond the maximum size of usize. ```rust // this will panic at runtime b"0123456789abcdef".repeat(usize::MAX); ``` -------------------------------- ### Get and modify Binary entry in MetadataMap Source: https://docs.rs/tonic/latest/tonic/metadata/struct.MetadataMap.html Demonstrates using `entry_bin` to get a Binary entry for in-place manipulation. Includes insertion, modification, and error handling for invalid keys or wrong types. ```rust let mut map = MetadataMap::default(); let headers = &[ "content-length-bin", "x-hello-bin", "Content-Length-bin", "x-world-bin", ]; for &header in headers { let counter = map.entry_bin(header).unwrap().or_insert(MetadataValue::from_bytes(b"")); *counter = MetadataValue::from_bytes(format!("{}{}", str::from_utf8(counter.to_bytes().unwrap().as_ref()).unwrap(), "1").as_bytes()); } assert_eq!(map.get_bin("content-length-bin").unwrap(), "11"); assert_eq!(map.get_bin("x-hello-bin").unwrap(), "1"); // Attempting to read a key of the wrong type fails by not // finding anything. map.append("host", "world".parse().unwrap()); assert!(!map.entry_bin("host").is_ok()); assert!(!map.entry_bin("host".to_string()).is_ok()); assert!(!map.entry_bin(&("host".to_string())).is_ok()); // Attempting to read an invalid key string fails by not // finding anything. assert!(!map.entry_bin("host{}-bin").is_ok()); assert!(!map.entry_bin("host{}-bin".to_string()).is_ok()); assert!(!map.entry_bin(&("host{}-bin".to_string())).is_ok()); ``` -------------------------------- ### Router::serve Source: https://docs.rs/tonic/latest/src/tonic/transport/server/mod.rs.html Consumes the router and starts the server, binding it to the specified address. ```APIDOC ## serve ### Description Consumes this [`Server`] creating a future that will execute the server on [tokio]'s default executor. ### Method `pub async fn serve(self, addr: SocketAddr) -> Result<(), super::Error>` ### Parameters - `addr` (SocketAddr): The address to bind the server to. ### Type Parameters - `ResBody`: The type of the response body, which must implement `http_body::Body` with `Data = Bytes` and be `Send + 'static`. Its error type must be convertible into `crate::BoxError`. ``` -------------------------------- ### Example: Setting and Checking Sensitivity Source: https://docs.rs/tonic/latest/src/tonic/metadata/value.rs.html Demonstrates how to use `set_sensitive` and `is_sensitive` with `AsciiMetadataValue`. ```rust # use tonic::metadata::* let mut val = AsciiMetadataValue::from_static("my secret"); val.set_sensitive(true); assert!(val.is_sensitive()); val.set_sensitive(false); assert!(!val.is_sensitive()); ``` -------------------------------- ### Tonic Server Configuration Example Source: https://docs.rs/tonic/latest/src/tonic/transport/mod.rs.html Illustrates setting up a Tonic server with TLS, concurrency limits, and adding a service. Requires the 'rustls' feature. ```rust # use std::convert::Infallible; # #[cfg(feature = "rustls")] # use tonic::transport::{Server, Identity, ServerTlsConfig}; # use tonic::body::Body; # use tower::Service; # #[cfg(feature = "rustls")] # async fn do_thing() -> Result<(), Box> { # #[derive(Clone)] # pub struct Svc; # impl Service> for Svc { # type Response = hyper::Response; # type Error = Infallible; # type Future = std::future::Ready>; # fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> std::task::Poll> { # Ok(()).into() # } # fn call(&mut self, _req: hyper::Request) -> Self::Future { # unimplemented!() # } # } # impl tonic::server::NamedService for Svc { # const NAME: &'static str = "some_svc"; # } # let my_svc = Svc; let cert = std::fs::read_to_string("server.pem")?; let key = std::fs::read_to_string("server.key")?; let addr = "[::1]:50051".parse()?; Server::builder() .tls_config(ServerTlsConfig::new() .identity(Identity::from_pem(&cert, &key)))? .concurrency_limit_per_connection(256) .add_service(my_svc) .serve(addr) .await?; # Ok(()) # } ``` -------------------------------- ### Run Axum Router with axum::serve Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html This example demonstrates how to create a simple Axum application and serve it using `axum::serve` with a `tokio::net::TcpListener`. ```rust use axum::{ routing::get, Router, }; let app = Router::new().route("/", get(|| async { "Hi!" })); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); ``` -------------------------------- ### Iterate Over Slice Elements Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Use `iter` to get an iterator that yields references to each element in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Basic Router Setup with Fallbacks Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html Demonstrates setting up a router with a root route, a default fallback, and a method not allowed fallback. The default fallback handles requests to undefined routes, while the method not allowed fallback handles requests to defined routes with unsupported HTTP methods. ```rust use axum::response::IntoResponse; use axum::routing::get; use axum::Router; async fn hello_world() -> impl IntoResponse { "Hello, world!\n" } async fn default_fallback() -> impl IntoResponse { "Default fallback\n" } async fn handle_405() -> impl IntoResponse { "Method not allowed fallback" } #[tokio::main] async fn main() { let router = Router::new() .route("/", get(hello_world)) .fallback(default_fallback) .method_not_allowed_fallback(handle_405); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, router).await.unwrap(); } ``` -------------------------------- ### Get element offset within a slice Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Calculates the byte offset of a given element reference from the start of the slice. Returns `None` if the element reference is not aligned to the start of an element. This method uses pointer arithmetic and does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### query Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html Get the query string of this `Uri`, starting after the `?`. The query component is indicated by the first question mark character and terminated by a number sign character or by the end of the URI. ```APIDOC ## query ### Description Get the query string of this `Uri`, starting after the `?`. The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI’s scheme and naming authority (if any). The query component is indicated by the first question mark (“?”) character and terminated by a number sign (“#”) character or by the end of the URI. ### Method `pub fn query(&self) -> Option<&str>` ### Examples Absolute URI ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` Relative URI with a query string component ```rust let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap(); // ... (example continues in source, but is truncated here) ``` ``` -------------------------------- ### Get the query string of a relative Uri Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html This example shows how to retrieve the query string from a relative URI. The `query()` method works for both absolute and relative URIs that contain a query component. ```rust let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap(); ``` -------------------------------- ### Compiling Protobufs with Tonic Build Source: https://docs.rs/tonic/latest/tonic/macro.include_file_descriptor_set.html This example shows how to configure `tonic-build` to compile protobuf files and specify the output path for the file descriptor set. ```rust let descriptor_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("my_descriptor.bin") tonic_build::configure() .file_descriptor_set_path(&descriptor_path) .compile_protos(&["proto/reflection.proto"], &["proto/"])?; ``` -------------------------------- ### Tonic Client Configuration Example Source: https://docs.rs/tonic/latest/src/tonic/transport/mod.rs.html Demonstrates how to configure a Tonic client with TLS, timeouts, rate limiting, and concurrency limits. Requires the 'rustls' feature. ```rust # #[cfg(feature = "rustls")] # use tonic::transport::{Channel, Certificate, ClientTlsConfig}; # use std::time::Duration; # use tonic::client::GrpcService;; # use http::Request; # #[cfg(feature = "rustls")] # async fn do_thing() -> Result<(), Box> { let cert = std::fs::read_to_string("ca.pem")?; let mut channel = Channel::from_static("https://example.com") .tls_config(ClientTlsConfig::new() .ca_certificate(Certificate::from_pem(&cert)) .domain_name("example.com".to_string()))? .timeout(Duration::from_secs(5)) .rate_limit(5, Duration::from_secs(1)) .concurrency_limit(256) .connect() .await?; channel.call(Request::new(tonic::body::empty_body())).await?; # Ok(()) # } ``` -------------------------------- ### get Source: https://docs.rs/tonic/latest/tonic/metadata/struct.OccupiedEntry.html Get a reference to the first value in the entry. Values are stored in insertion order. ```APIDOC ## get ### Description Get a reference to the first value in the entry. Values are stored in insertion order. ### Method `get(&self) -> &MetadataValue` ### Panics `get` panics if there are no values associated with the entry. ### Examples ```rust let mut map = MetadataMap::new(); map.insert("host", "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host").unwrap() { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` ``` -------------------------------- ### Server Builder Initialization Source: https://docs.rs/tonic/latest/tonic/transport/struct.Server.html Create a new server builder to configure a `Server` instance. ```rust pub fn builder() -> Self ``` -------------------------------- ### Example: Parsing a metadata key from a static string Source: https://docs.rs/tonic/latest/src/tonic/metadata/key.rs.html Demonstrates creating an AsciiMetadataKey from a valid static string and comparing it with one created from bytes. ```rust # use tonic::metadata::* # // Parsing a metadata key let CUSTOM_KEY: &'static str = "custom-key"; let a = AsciiMetadataKey::from_bytes(b"custom-key").unwrap(); let b = AsciiMetadataKey::from_static(CUSTOM_KEY); assert_eq!(a, b); ``` -------------------------------- ### Initialize Grpc Server Source: https://docs.rs/tonic/latest/tonic/server/struct.Grpc.html Creates a new gRPC server instance with the provided Codec. ```rust pub fn new(codec: T) -> Self ``` -------------------------------- ### Get the number of metadata entries Source: https://docs.rs/tonic/latest/tonic/metadata/struct.MetadataMap.html Use `len()` to get the total count of metadata values, including duplicates for the same key. Useful for monitoring map size. ```rust let mut map = MetadataMap::new(); assert_eq!(0, map.len()); map.insert("x-host-ip", "127.0.0.1".parse().unwrap()); map.insert_bin("x-host-name-bin", MetadataValue::from_bytes(b"localhost")); assert_eq!(2, map.len()); map.append("x-host-ip", "text/html".parse().unwrap()); assert_eq!(3, map.len()); ``` -------------------------------- ### Configure and Serve Tonic Server Source: https://docs.rs/tonic/latest/tonic/transport/index.html Example of configuring a Tonic server with TLS identity, concurrency limits, and adding a service before serving. ```rust let cert = std::fs::read_to_string("server.pem")?; let key = std::fs::read_to_string("server.key")?; let addr = "[::1]:50051".parse()?; Server::builder() .tls_config(ServerTlsConfig::new() .identity(Identity::from_pem(&cert, &key)))? .concurrency_limit_per_connection(256) .add_service(my_svc) .serve(addr) .await?; ``` -------------------------------- ### Getting the First Value from an OccupiedEntry Source: https://docs.rs/tonic/latest/tonic/metadata/struct.OccupiedEntry.html Shows how to get a reference to the first value associated with an occupied metadata entry. Note that this method panics if no values exist. ```rust let mut map = MetadataMap::new(); map.insert("host", "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host").unwrap() { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` -------------------------------- ### ServerTlsConfig::new Source: https://docs.rs/tonic/latest/tonic/transport/server/struct.ServerTlsConfig.html Creates a new ServerTlsConfig with default settings. ```APIDOC ## ServerTlsConfig::new ### Description Creates a new `ServerTlsConfig`. ### Method `ServerTlsConfig::new()` ### Returns A new instance of `ServerTlsConfig`. ``` -------------------------------- ### Get the port as a u16 Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html The `port_u16()` method provides a convenient way to get the port number directly as a `u16`. It returns `None` if the port is not specified or the URI is relative. ```rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.port_u16(), Some(80)); ``` -------------------------------- ### Result::unwrap_unchecked Example Source: https://docs.rs/tonic/latest/tonic/type.Result.html Provides an example of `unwrap_unchecked`, which returns the `Ok` value without checking if the `Result` is `Err`. This method is unsafe and calling it on an `Err` results in undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Basic Router with TraceLayer Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html Demonstrates creating a basic Axum Router and applying a TraceLayer middleware to all routes. ```rust let app = Router::new() .route("/foo", get(|| async {})) .route("/bar", get(|| async {})) .layer(TraceLayer::new_for_http()); ``` -------------------------------- ### take Source: https://docs.rs/tonic/latest/tonic/codec/struct.DecodeBuf.html Creates an adaptor which will read at most `limit` bytes from the buffer. ```APIDOC ## fn take(self, limit: usize) -> Take ### Description Creates an adaptor which will read at most `limit` bytes from `self`. ### Parameters - **limit** (usize): The maximum number of bytes to read. ### Signature ```rust fn take(self, limit: usize) -> Take ``` ### Returns A `Take` adaptor that limits the number of bytes read from the buffer. ``` -------------------------------- ### Get Slice as Underlying Array Reference Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Attempt to get a reference to the underlying array using `as_array`. Returns `Some` if the specified size `N` matches the slice length, otherwise `None`. ```rust let data = [1, 2, 3]; let slice = &data[..]; // This will succeed because N=3 matches slice length let array_ref: Option<&[i32; 3]> = slice.as_array::<3>(); assert!(array_ref.is_some()); // This will fail because N=2 does not match slice length let array_ref_fail: Option<&[i32; 2]> = slice.as_array::<2>(); assert!(array_ref_fail.is_none()); ``` -------------------------------- ### Get and modify ASCII entry in MetadataMap Source: https://docs.rs/tonic/latest/tonic/metadata/struct.MetadataMap.html Shows how to get an ASCII entry for in-place manipulation using `entry`. Handles insertion and modification, and demonstrates error handling for invalid keys. ```rust let mut map = MetadataMap::default(); let headers = &[ "content-length", "x-hello", "Content-Length", "x-world", ]; for &header in headers { let counter = map.entry(header).unwrap().or_insert("".parse().unwrap()); *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap(); } assert_eq!(map.get("content-length").unwrap(), "11"); assert_eq!(map.get("x-hello").unwrap(), "1"); // Gracefully handles parting invalid key strings assert!(!map.entry("a{}b").is_ok()); // Attempting to read a key of the wrong type fails by not // finding anything. map.append_bin("host-bin", MetadataValue::from_bytes(b"world")); assert!(!map.entry("host-bin").is_ok()); assert!(!map.entry("host-bin".to_string()).is_ok()); assert!(!map.entry(&("host-bin".to_string())).is_ok()); // Attempting to read an invalid key string fails by not // finding anything. assert!(!map.entry("host{}").is_ok()); assert!(!map.entry("host{}".to_string()).is_ok()); assert!(!map.entry(&("host{}".to_string())).is_ok()); ``` -------------------------------- ### CertificateDer Usage Examples Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Demonstrates how to load certificates from PEM files or byte slices using CertificateDer. ```APIDOC ```rust use rustls_pki_types::{CertificateDer, pem::PemObject}; // load several from a PEM file let certs: Vec<_> = CertificateDer::pem_file_iter("tests/data/certificate.chain.pem") .unwrap() .collect(); assert_eq!(certs.len(), 3); // or one from a PEM byte slice... CertificateDer::from_pem_slice(byte_slice).unwrap(); // or several from a PEM byte slice let certs: Vec<_> = CertificateDer::pem_slice_iter(byte_slice) .collect(); assert_eq!(certs.len(), 3); ``` ``` -------------------------------- ### Basic Router Initialization and Serving Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html Initializes a Tokio TCP listener and serves an Axum router. This is a fundamental setup for running an Axum application. ```rust let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, routes).await.unwrap(); ``` -------------------------------- ### Remove Prefix from Slice Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Returns a subslice with the prefix removed if the slice starts with the given `prefix`. Returns `None` if the slice does not start with the `prefix`. An empty `prefix` returns the original slice. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); ``` ```rust let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### Handling All Requests with Fallback Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html Shows an example of using `Router::new().fallback(...)` to accept all requests when no other routes are defined. This approach is less optimal than running a handler directly if no routing is needed. ```rust use axum::Router; async fn handler() {} let app = Router::new().fallback(handler); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); ``` -------------------------------- ### DecodeBuf Usage Example Source: https://docs.rs/tonic/latest/src/tonic/codec/buffer.rs.html Demonstrates the usage of DecodeBuf, including initialization, checking remaining capacity, advancing the buffer, and copying data. ```rust #[test] fn decode_buf() { let mut payload = BytesMut::with_capacity(100); payload.put(&vec![0u8; 50][..]); let mut buf = DecodeBuf::new(&mut payload, 20); assert_eq!(buf.len, 20); assert_eq!(buf.remaining(), 20); assert_eq!(buf.chunk().len(), 20); buf.advance(10); assert_eq!(buf.remaining(), 10); let mut out = [0; 5]; buf.copy_to_slice(&mut out); assert_eq!(buf.remaining(), 5); assert_eq!(buf.chunk().len(), 5); assert_eq!(buf.copy_to_bytes(5).len(), 5); assert!(!buf.has_remaining()); } ``` -------------------------------- ### Get Last N Elements of a Slice Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Use `last_chunk` to get a reference to the last `N` elements of a slice. Returns `None` if the slice is shorter than `N`. Handles `N=0` by returning an empty slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Configure and Connect Tonic Client Source: https://docs.rs/tonic/latest/tonic/transport/index.html Example of configuring a Tonic client with TLS, domain name, timeout, and rate limiting before connecting. ```rust let cert = std::fs::read_to_string("ca.pem")?; let mut channel = Channel::from_static("https://example.com") .tls_config(ClientTlsConfig::new() .ca_certificate(Certificate::from_pem(&cert)) .domain_name("example.com".to_string()))? .timeout(Duration::from_secs(5)) .rate_limit(5, Duration::from_secs(1)) .concurrency_limit(256) .connect() .await?; channel.call(Request::new(tonic::body::empty_body())).await?; ``` -------------------------------- ### port_u16 Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html Get the port of this `Uri` as a `u16`. ```APIDOC ## port_u16 ### Description Get the port of this `Uri` as a `u16`. ### Method `pub fn port_u16(&self) -> Option` ### Example ```rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.port_u16(), Some(80)); ``` ``` -------------------------------- ### Initialize ClientTlsConfig Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/tls.rs.html Creates a new `ClientTlsConfig` instance using the default configuration. This is the starting point for building custom TLS settings. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### ClientTlsConfig::new Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.ClientTlsConfig.html Creates a new `ClientTlsConfig` using Rustls. ```APIDOC ## ClientTlsConfig::new ### Description Creates a new `ClientTlsConfig` using Rustls. ### Method ```rust pub fn new() -> Self ``` ``` -------------------------------- ### scheme_str Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html Get the scheme of this `Uri` as a `&str`. ```APIDOC ## scheme_str ### Description Get the scheme of this `Uri` as a `&str`. ### Method `pub fn scheme_str(&self) -> Option<&str>` ### Example ```rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme_str(), Some("http")); ``` ``` -------------------------------- ### Router::serve Source: https://docs.rs/tonic/latest/tonic/transport/server/struct.Router.html Consumes the router and starts a server on the specified address using Tokio's default executor. ```APIDOC ## Router::serve ### Description Consumes this `Router` and creates a future that executes the server on Tokio's default executor. ### Method `serve` ### Parameters - **addr**: `SocketAddr` - The address to bind the server to. ### Returns - `Result<(), Error>` - A future that resolves to `Ok(())` on success or an `Err(Error)` on failure. ``` -------------------------------- ### Get Endpoint URI Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the URI of the endpoint. ```APIDOC ## pub fn uri ### Description Get the endpoint uri. ### Returns - **&Uri** - The endpoint's URI. ### Example ```rust let endpoint = Endpoint::from_static("https://example.com"); assert_eq!(endpoint.uri(), &Uri::from_static("https://example.com")); ``` ``` -------------------------------- ### Buffer Growth Example Source: https://docs.rs/tonic/latest/tonic/codec/struct.BufferSettings.html Illustrates how Tonic's buffer grows to accommodate larger messages. The buffer grows in increments of buffer_size, rounding up to the next increment if necessary. ```text Buffer start: | 8kb | Message received: | 24612 bytes | Buffer grows: | 8kb | 8kb | 8kb | 8kb | ``` -------------------------------- ### get_tcp_keepalive Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/endpoint.rs.html Gets the configured TCP keepalive setting. ```APIDOC ## get_tcp_keepalive ### Description Gets the configured TCP keepalive setting. If `None` is specified, keepalive is disabled. Otherwise, the duration specified is the time to remain idle before sending TCP keepalive probes. ### Method `fn get_tcp_keepalive(&self) -> Option` ### Parameters None ### Response - `Option`: The TCP keepalive duration, or `None` if disabled. ``` -------------------------------- ### Building a Uri with Builder Pattern Source: https://docs.rs/tonic/latest/tonic/transport/struct.Uri.html Illustrates creating a Uri using a builder pattern, allowing for step-by-step construction of scheme, authority, and path. Useful for programmatic Uri generation. ```rust use http::Uri; let uri = Uri::builder() .scheme("https") .authority("hyper.rs") .path_and_query("/") .build() .unwrap(); ``` -------------------------------- ### get_connect_timeout Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/endpoint.rs.html Gets the configured connect timeout duration. ```APIDOC ## get_connect_timeout ### Description Gets the configured connect timeout duration. ### Method `fn get_connect_timeout(&self) -> Option` ### Parameters None ### Response - `Option`: The connect timeout duration, or `None` if not set. ``` -------------------------------- ### Response::metadata_mut Source: https://docs.rs/tonic/latest/tonic/struct.Response.html Gets a mutable reference to the response metadata. ```APIDOC ## Response::metadata_mut ### Description Get a mutable reference to the response metadata. ### Signature ```rust pub fn metadata_mut(&mut self) -> &mut MetadataMap ``` ``` -------------------------------- ### EncodeBuf Usage Example Source: https://docs.rs/tonic/latest/src/tonic/codec/buffer.rs.html Illustrates the basic usage of EncodeBuf, showing how to initialize it, advance the mutable buffer, and put data into it. ```rust #[test] fn encode_buf() { let mut bytes = BytesMut::with_capacity(100); let mut buf = EncodeBuf::new(&mut bytes); let initial = buf.remaining_mut(); unsafe { buf.advance_mut(20) }; assert_eq!(buf.remaining_mut(), initial - 20); buf.put_u8(b'a'); assert_eq!(buf.remaining_mut(), initial - 20 - 1); } ``` -------------------------------- ### Response::metadata Source: https://docs.rs/tonic/latest/tonic/struct.Response.html Gets a reference to the custom response metadata. ```APIDOC ## Response::metadata ### Description Get a reference to the custom response metadata. ### Signature ```rust pub fn metadata(&self) -> &MetadataMap ``` ``` -------------------------------- ### Response::get_mut Source: https://docs.rs/tonic/latest/tonic/struct.Response.html Gets a mutable reference to the response message. ```APIDOC ## Response::get_mut ### Description Get a mutable reference to the message ### Signature ```rust pub fn get_mut(&mut self) -> &mut T ``` ``` -------------------------------- ### Creating and Using gRPC Status Source: https://docs.rs/tonic/latest/src/tonic/status.rs.html Demonstrates how to create `Status` objects using both the generic `new` function and specialized associated functions for specific gRPC codes. It also shows how to retrieve the status code. ```rust use tonic::{Status, Code}; let status1 = Status::new(Code::InvalidArgument, "name is invalid"); let status2 = Status::invalid_argument("name is invalid"); assert_eq!(status1.code(), Code::InvalidArgument); assert_eq!(status1.code(), status2.code()); ``` -------------------------------- ### And Then with File Metadata Example Source: https://docs.rs/tonic/latest/tonic/type.Result.html Demonstrates chaining `and_then` with file system operations to handle potential errors during metadata retrieval. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Response::get_ref Source: https://docs.rs/tonic/latest/tonic/struct.Response.html Gets an immutable reference to the response message. ```APIDOC ## Response::get_ref ### Description Get a immutable reference to `T`. ### Signature ```rust pub fn get_ref(&self) -> &T ``` ``` -------------------------------- ### impl Any for T Source: https://docs.rs/tonic/latest/tonic/metadata/struct.ValuesMut.html Provides the `type_id` method to get the `TypeId` of a type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Expect: Recommended Message Style for Environment Variables Source: https://docs.rs/tonic/latest/tonic/type.Result.html Demonstrates the recommended style for expect messages, focusing on the expected state of the environment. This helps in debugging by clearly stating the prerequisite. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Create a new gRPC server handler Source: https://docs.rs/tonic/latest/src/tonic/server/grpc.rs.html Instantiates a new `Grpc` server handler with a given codec. Default compression settings are applied. ```rust pub fn new(codec: T) -> Self { Self { codec, accept_compression_encodings: EnabledCompressionEncodings::default(), send_compression_encodings: EnabledCompressionEncodings::default(), max_decoding_message_size: None, max_encoding_message_size: None, } } ``` -------------------------------- ### get_tcp_nodelay Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/endpoint.rs.html Gets the value of the TCP_NODELAY option for accepted connections. ```APIDOC ## get_tcp_nodelay ### Description Gets the value of the TCP_NODELAY option for accepted connections. ### Method `fn get_tcp_nodelay(&self) -> bool` ### Parameters None ### Response - `bool`: `true` if TCP_NODELAY is enabled, `false` otherwise. ``` -------------------------------- ### Define Multiple Routes with Various Path Types Source: https://docs.rs/tonic/latest/tonic/service/struct.AxumRouter.html Example demonstrating the definition of multiple routes with static paths, captures, and wildcards. It also shows how to extract path parameters using `Path`. ```rust use axum:: Router, routing::{ get, delete, }, extract::Path, ; let app = Router::new() .route("/", get(root)) .route("/users", get(list_users).post(create_user)) .route("/users/{id}", get(show_user)) .route("/api/{version}/users/{id}/action", delete(do_users_action)) .route("/assets/{*path}", get(serve_asset)); async fn root() {{}} async fn list_users() {{}} async fn create_user() {{}} async fn show_user(Path(id): Path) {{}} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {{}} async fn serve_asset(Path(path): Path) {{}} ``` -------------------------------- ### try_get_i8 Source: https://docs.rs/tonic/latest/tonic/codec/struct.DecodeBuf.html Attempts to get a signed 8-bit integer from the buffer. ```APIDOC ## fn try_get_i8(&mut self) -> Result ### Description Gets a signed 8 bit integer from `self`. ### Returns - **Result** - Ok(i8) if successful, or an Err(TryGetError) if the buffer does not contain enough data. ``` -------------------------------- ### try_get_u8 Source: https://docs.rs/tonic/latest/tonic/codec/struct.DecodeBuf.html Attempts to get an unsigned 8-bit integer from the buffer. ```APIDOC ## fn try_get_u8(&mut self) -> Result ### Description Gets an unsigned 8 bit integer from `self`. ### Returns - **Result** - Ok(u8) if successful, or an Err(TryGetError) if the buffer does not contain enough data. ``` -------------------------------- ### MetadataKey Creation Source: https://docs.rs/tonic/latest/src/tonic/metadata/key.rs.html Demonstrates how to create MetadataKey instances from byte slices and static strings, including validation for ASCII and binary keys. ```APIDOC ## MetadataKey Creation Methods ### `from_bytes` Converts a slice of bytes to a `MetadataKey`. This function normalizes the input and validates it against the `ValueEncoding`. **Parameters** - `src` (&[u8]): The byte slice to convert. **Returns** - `Result`: A `MetadataKey` if successful, or an `InvalidMetadataKey` error. ### `from_static` Converts a static string to a `MetadataKey`. This function panics if the static string is an invalid metadata key. It requires the string to contain only lowercase characters, numerals, and symbols as per HTTP/2.0 specification. **Parameters** - `src` (&'static str): The static string to convert. **Returns** - `Self`: A `MetadataKey` instance. **Panics** - If the provided static string is not a valid metadata key. ### Examples ```rust # use tonic::metadata::*; // Creating an ASCII metadata key from bytes let key_bytes = AsciiMetadataKey::from_bytes(b"custom-key").unwrap(); // Creating an ASCII metadata key from a static string const CUSTOM_KEY: &'static str = "custom-key"; let key_static = AsciiMetadataKey::from_static(CUSTOM_KEY); assert_eq!(key_bytes, key_static); // Example of invalid key creation (will panic) // AsciiMetadataKey::from_static("invalid-key!"); // BinaryMetadataKey::from_static("ascii-key"); ``` ### `as_str` Returns a `str` representation of the metadata key. The returned string will always be lower case. **Returns** - `&str`: The string representation of the metadata key. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/tonic/latest/tonic/metadata/enum.Binary.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Returns the number of elements in a byte slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Setting and Verifying User Agent Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/service/user_agent.rs.html Demonstrates how to insert a custom user agent header into a request and verify it in a service implementation. This is useful for identifying your client and its version. ```rust .insert(USER_AGENT, HeaderValue::from_static("request-ua/x.y")); let expected_user_agent = format!("request-ua/x.y Greeter 1.1 {TONIC_USER_AGENT}"); let mut ua = UserAgent::new( TestSvc { expected_user_agent, }, Some(HeaderValue::from_static("Greeter 1.1")), ); let _ = ua.call(req).await; ``` -------------------------------- ### Get Connect Timeout Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the configured connect timeout duration. ```APIDOC ## pub fn get_connect_timeout ### Description Get the connect timeout. ### Returns - **Option** - The connect timeout duration, if set. ``` -------------------------------- ### OccupiedEntry::get Source: https://docs.rs/tonic/latest/src/tonic/metadata/map.rs.html Gets a reference to the first value in an occupied entry. ```APIDOC ## OccupiedEntry::get ### Description Get a reference to the first value in the entry. Values are stored in insertion order. ### Panics `get` panics if there are no values associated with the entry. ### Method `pub fn get(&self) -> &MetadataValue` ### Examples ```rust # use tonic::metadata::* let mut map = MetadataMap::new(); map.insert("host", "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host").unwrap() { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); ``` ``` -------------------------------- ### Create a new gRPC client Source: https://docs.rs/tonic/latest/tonic/client/struct.Grpc.html Constructs a new gRPC client using a provided GrpcService. This is the basic way to create a client instance. ```rust let client = TestClient::new(channel); ``` -------------------------------- ### iter Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Returns an iterator over the slice, yielding all items from start to end. ```APIDOC ## iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method `iter` ### Returns - `Iter<'_, T>`: An iterator over the elements of the slice. ``` -------------------------------- ### ServerStreamingService Implementor Example Source: https://docs.rs/tonic/latest/tonic/server/trait.ServerStreamingService.html Shows how a generic implementation of `ServerStreamingService` can be derived from an existing `tower_service::Service` that returns a `Response` containing a `Stream`. ```rust impl ServerStreamingService for T where T: Service, Response = Response, Error = Status>, S: Stream> ``` -------------------------------- ### Example: Panics on '-bin' suffix for Ascii key Source: https://docs.rs/tonic/latest/src/tonic/metadata/key.rs.html Demonstrates that attempting to create an `AsciiMetadataKey` from a string ending in '-bin' will result in a panic, as this suffix is reserved for binary metadata. ```rust # use tonic::metadata::* // Parsing a -bin metadata key as an Ascii key. let b = AsciiMetadataKey::from_static("hello-bin"); // This line panics! ``` -------------------------------- ### as_array Source: https://docs.rs/tonic/latest/tonic/transport/struct.CertificateDer.html Gets a reference to the underlying array if N matches the slice length. ```APIDOC ## as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. If `N` is not exactly equal to the length of `self`, then this method returns `None`. ### Method `as_array` ### Parameters #### Type Parameters - **N**: `usize` - The expected length of the array. ### Returns - `Option<&[T; N]>`: A reference to the underlying array if its length is `N`, otherwise `None`. ``` -------------------------------- ### Get TCP Keep-Alive Retries Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the number of TCP keep-alive retries. ```APIDOC ## pub fn get_tcp_keepalive_retries ### Description Get whether TCP keepalive retries. ### Returns - **Option** - The number of TCP keep-alive retries, if set. ``` -------------------------------- ### connect Source: https://docs.rs/tonic/latest/src/tonic/transport/channel/endpoint.rs.html Creates a channel from the endpoint configuration and immediately attempts to connect. ```APIDOC ## connect ### Description Creates a channel from the endpoint configuration and immediately attempts to connect. ### Method `async fn connect(&self) -> Result` ### Parameters None ### Request Example ```rust // Example usage: // let channel = endpoint.connect().await?; ``` ### Response #### Success Response - `Channel`: A connected channel. #### Error Response - `Error`: If the connection fails. ``` -------------------------------- ### Get TCP Keep-Alive Interval Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the TCP keep-alive interval setting. ```APIDOC ## pub fn get_tcp_keepalive_interval ### Description Get whether TCP keepalive interval. ### Returns - **Option** - The TCP keep-alive interval, if set. ``` -------------------------------- ### Server::builder Source: https://docs.rs/tonic/latest/src/tonic/transport/server/mod.rs.html Creates a new server builder that can be used to configure a [`Server`]. This is the entry point for customizing server settings. ```APIDOC ## Server::builder ### Description Creates a new server builder that can be used to configure a [`Server`]. This is the entry point for customizing server settings. ### Method Associated function (constructor) ### Endpoint N/A (constructor) ### Parameters None ### Response Returns a new `Server` builder instance. ``` -------------------------------- ### Example: Panics on non-bin key for Binary key Source: https://docs.rs/tonic/latest/src/tonic/metadata/key.rs.html Illustrates that attempting to create a `BinaryMetadataKey` from a string that does not end in '-bin' will cause a panic, as it violates the convention for binary metadata. ```rust # use tonic::metadata::* // Parsing a non-bin metadata key as an Binary key. let b = BinaryMetadataKey::from_static("hello"); // This line panics! ``` -------------------------------- ### Get TCP No Delay Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the value of the TCP_NODELAY option for accepted connections. ```APIDOC ## pub fn get_tcp_nodelay ### Description Get the value of `TCP_NODELAY` option for accepted connections. ### Returns - **bool** - True if TCP_NODELAY is enabled, false otherwise. ``` -------------------------------- ### Get TCP Keep-Alive Interval Source: https://docs.rs/tonic/latest/tonic/transport/channel/struct.Endpoint.html Retrieves the configured TCP keep-alive interval. ```rust pub fn get_tcp_keepalive_interval(&self) -> Option ```