}
}
#[route(GET "/api/health")]
async fn health() -> Result<&'static str> {
Ok("ok")
}
// Reads a JSON request body and echoes it back as a JSON response.
#[route(POST "/api/users")]
async fn create_user(Json(user): Json) -> Result> {
Ok(Json(user))
}
pub fn router() -> Router {
Router::builder()
.layout(root_layout)
.layer(api_log)
.page(home)
.page(users_list)
.page(user_profile)
.route(health)
.route(create_user)
.build()
}
```
--------------------------------
### Auto-discovery Setup Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/index.html?search=
The same application logic as the manual setup, but using auto-discovery to register handlers.
```rust
use topcoat::router::{Router, RouterBuilderDiscoverExt};
// The page, layout, layer, and route definitions are identical. Only the
// router function changes.
pub fn router() -> Router {
Router::builder().discover().build()
}
```
--------------------------------
### start
Source: https://docs.rs/topcoat/0.1.3/topcoat/index.html
Start a Topcoat router on the configured host and port.
```APIDOC
## start
### Description
Start a Topcoat router on the configured host and port.
```
--------------------------------
### pub async fn start(router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html
Starts a Topcoat router on the configured host and port. The listener binds to the HOST and PORT environment variables, or defaults to 127.0.0.1:3000 if unset.
```APIDOC
## pub async fn start(router: Router) -> Result<(), Error>
### Description
Starts a Topcoat router on the configured host and port. The listener binds to the `HOST` and `PORT` environment variables, or `127.0.0.1` and `3000` when unset.
### Parameters
- **router** (Router) - Required - The router instance to be started.
### Errors
Returns `Err` if `HOST`/`PORT` are invalid, if binding the TCP listener fails, or if serving the router fails.
```
--------------------------------
### pub async fn start(router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html?search=
Starts a Topcoat router on the configured host and port. The listener binds to the HOST and PORT environment variables, or defaults to 127.0.0.1:3000 if unset.
```APIDOC
## start
### Description
Starts a Topcoat router on the configured host and port. The listener binds to the `HOST` and `PORT` environment variables, or `127.0.0.1` and `3000` when unset.
### Signature
`pub async fn start(router: Router) -> Result<(), Error>`
### Parameters
- **router** (Router) - The router instance to be started.
### Errors
Returns `Err` if `HOST`/`PORT` are invalid, if binding the TCP listener fails, or if serving the router fails.
```
--------------------------------
### Slice Get Method Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the get method on a slice.
```rust
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
```
--------------------------------
### pub async fn start(router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Starts a Topcoat router on the configured host and port. The listener binds to the HOST and PORT environment variables, or defaults to 127.0.0.1:3000 if unset.
```APIDOC
## pub async fn start(router: Router) -> Result<(), Error>
### Description
Starts a Topcoat router on the configured host and port. The listener binds to the `HOST` and `PORT` environment variables, or `127.0.0.1` and `3000` when unset.
### Parameters
- **router** (Router) - The router instance to be started.
### Errors
Returns `Err` if `HOST`/`PORT` are invalid, if binding the TCP listener fails, or if serving the router fails.
```
--------------------------------
### Initialize and Start Router
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.Router.html
Demonstrates the standard pattern for building a router using discovery and starting the application.
```rust
use topcoat::router::{Router, RouterBuilderDiscoverExt};
let router = Router::builder().discover().build();
topcoat::start(router).await?;
```
--------------------------------
### pub async fn start(router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html?search=u32+-%3E+bool
Starts a Topcoat router on the configured host and port. The listener binds to the HOST and PORT environment variables, or defaults to 127.0.0.1:3000 if unset.
```APIDOC
## Function: start
### Description
Starts a Topcoat router on the configured host and port. The listener binds to the `HOST` and `PORT` environment variables, or `127.0.0.1` and `3000` when unset.
### Signature
`pub async fn start(router: Router) -> Result<(), Error>`
### Parameters
- **router** (Router) - The router instance to be started.
### Errors
Returns `Err` if `HOST`/`PORT` are invalid, if binding the TCP listener fails, or if serving the router fails.
```
--------------------------------
### pub async fn start(router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html?search=std%3A%3Avec
Starts a Topcoat router on the configured host and port. The listener binds to the HOST and PORT environment variables, or defaults to 127.0.0.1:3000.
```APIDOC
## pub async fn start(router: Router) -> Result<(), Error>
### Description
Starts a Topcoat router on the configured host and port. The listener binds to the `HOST` and `PORT` environment variables, or defaults to `127.0.0.1:3000` when these variables are unset.
### Parameters
- **router** (Router) - The router instance to be started.
### Returns
- **Result<(), Error>** - Returns `Ok(())` on success, or an `Err` if `HOST`/`PORT` are invalid, if binding the TCP listener fails, or if serving the router fails.
```
--------------------------------
### pub async fn start(cx: &Cx) -> Result
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/fn.start.html?search=
Starts a new session, issuing a fresh token to the client. This function always generates a new token and should be used to record the returned Session in the application's session storage.
```APIDOC
## Function: start
### Description
Starts a new session, issuing a fresh token to the client. Always generates a new token (never reuses one the request presented), so calling this on login also protects against session fixation. Record the returned `Session` in the application’s session storage.
### Signature
`pub async fn start(cx: &Cx) -> Result`
### Parameters
- **cx** (&Cx) - Required - The context object used to start the session.
### Returns
- **Result** - Returns a `Session` object on success, or an `Error` if the token store fails to issue the token.
```
--------------------------------
### pub async fn start(cx: &Cx) -> Result
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/fn.start.html
Starts a new session, issuing a fresh token to the client. This function always generates a new token, ensuring protection against session fixation.
```APIDOC
## pub async fn start(cx: &Cx) -> Result
### Description
Starts a new session, issuing a fresh token to the client. Always generates a new token (never reuses one the request presented), so calling this on login also protects against session fixation. Record the returned `Session` in the application’s session storage.
### Parameters
- **cx** (&Cx) - Required - The context object used to start the session.
### Returns
- **Result** - Returns a `Session` object on success, or an `Error` if the token store fails to issue the token.
```
--------------------------------
### Asset path resolution examples
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/index.html?search=
Examples of how different path formats are resolved by the asset! macro.
```rust
asset!("./ferris.png")
```
```rust
asset!("../shared/logo.png")
```
```rust
asset!("assets/logo.png")
```
```rust
asset!("/opt/app/logo.png")
```
```rust
asset!("https://example.com/logo.png")
```
--------------------------------
### Server Startup
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Functions to start the Topcoat server and bind to network addresses.
```APIDOC
## topcoat::start(router)
### Description
Starts the server using the provided router. Binds to `HOST` and `PORT` (defaults to 127.0.0.1:3000).
## topcoat::serve(router, listener)
### Description
Starts the server using a custom `TcpListener`.
```
--------------------------------
### Check for JSON content type
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/fn.content_type.html?search=
Example usage demonstrating how to verify if the request content type starts with application/json.
```rust
use topcoat::{context::Cx, router::content_type};
async fn is_json(cx: &Cx) -> bool {
content_type(cx).is_some_and(|value| value.starts_with("application/json"))
}
```
--------------------------------
### Serving the Router
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/index.html?search=
Start the server using the finalized router instance.
```rust
#[tokio::main]
async fn main() {
let router = my_app::router();
topcoat::start(router).await.unwrap();
}
```
--------------------------------
### pub async fn start(cx: &Cx) -> Result
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/fn.start.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Starts a new session, issuing a fresh token to the client. Always generates a new token, so calling this on login protects against session fixation. The returned Session should be recorded in the application's session storage.
```APIDOC
## Function: start
### Description
Starts a new session, issuing a fresh token to the client. This function always generates a new token, preventing session fixation attacks.
### Signature
`pub async fn start(cx: &Cx) -> Result`
### Parameters
- **cx** (&Cx) - The context required to initiate the session.
### Returns
- **Result** - Returns a `Session` object on success, or an `Error` if the token store fails to issue the token.
```
--------------------------------
### Slice Split First Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the split_first method on a slice.
```rust
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first() {
assert_eq!(first, &0);
assert_eq!(elements, &[1, 2]);
}
```
--------------------------------
### Slice First Element Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the first method on a slice.
```rust
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());
let w: &[i32] = &[];
assert_eq!(None, w.first());
```
--------------------------------
### pub async fn start(cx: &Cx) -> Result
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/fn.start.html?search=std%3A%3Avec
Starts a new session, issuing a fresh token to the client. Always generates a new token, so calling this on login also protects against session fixation. Record the returned Session in the application’s session storage.
```APIDOC
## Function: start
### Signature
`pub async fn start(cx: &Cx) -> Result`
### Description
Starts a new session, issuing a fresh token to the client. Always generates a new token (never reuses one the request presented), so calling this on login also protects against session fixation. Record the returned `Session` in the application’s session storage.
### Parameters
- **cx** (&Cx) - The context required to start the session.
### Returns
- **Result** - Returns a `Session` object on success, or an `Error` if the token store fails to issue the token.
```
--------------------------------
### Slice First Chunk Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the first_chunk method on a slice.
```rust
let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());
let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
```
--------------------------------
### Define Layout and Page
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/macro.module_router.html
Example of a root layout and a home page handler.
```rust
// src/app.rs: layout at "/" wraps all pages
#[layout]
async fn root_layout(slot: Slot<'_>) -> Result {
view! {
(slot.await?)
}
}
#[page]
async fn home() -> Result {
view! {
"Home"
}
}
```
--------------------------------
### Match URL start against route
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.PathBuf.html?search=
Checks if a concrete URL starts with the defined route path, allowing for extra trailing segments.
```rust
use topcoat_router::Path;
let path = Path::new("/settings");
// Extra trailing segments are allowed.
assert!(path.matches_start("/settings/profile"));
assert!(!path.matches_start("/dashboard"));
assert!(Path::new("/users/{id}").matches_start("/users/42/posts"));
```
--------------------------------
### Define Layer
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/macro.module_router.html
Example of a layer that wraps request handling.
```rust
// src/app/api.rs: wraps routes under /api
use topcoat::{
Result,
context::CxBuilder,
router::{Body, Next, Response, layer},
};
#[layer]
async fn api_log(cx: &mut CxBuilder, body: Body, next: Next<'_>) -> Result {
let response = next.run(cx, body).await?;
println!("API response: {}", response.status());
Ok(response)
}
```
--------------------------------
### Get Date Month
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the month from a Date.
```rust
assert_eq!(date!(2019-01-01).month(), Month::January);
assert_eq!(date!(2019-12-31).month(), Month::December);
```
--------------------------------
### Get Date Year
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the year from a Date.
```rust
assert_eq!(date!(2019-01-01).year(), 2019);
assert_eq!(date!(2019-12-31).year(), 2019);
assert_eq!(date!(2020-01-01).year(), 2020);
```
--------------------------------
### Get Date Ordinal
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the day of the year from a Date.
```rust
assert_eq!(date!(2019-01-01).ordinal(), 1);
assert_eq!(date!(2019-12-31).ordinal(), 365);
```
--------------------------------
### Get Date Day
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the day of the month from a Date.
```rust
assert_eq!(date!(2019-01-01).day(), 1);
assert_eq!(date!(2019-12-31).day(), 31);
```
--------------------------------
### Get Date ISO Week
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the ISO week number from a Date.
```rust
assert_eq!(date!(2019-01-01).iso_week(), 1);
assert_eq!(date!(2019-10-04).iso_week(), 40);
assert_eq!(date!(2020-01-01).iso_week(), 1);
assert_eq!(date!(2020-12-31).iso_week(), 53);
assert_eq!(date!(2021-01-01).iso_week(), 53);
```
--------------------------------
### pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.serve.html?search=
Starts the Topcoat router and notifies the dev server of readiness.
```APIDOC
## serve
### Description
Serve a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections. This calls `crate::dev::notify_ready` before handing the listener off to the router’s accept loop.
### Signature
`pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>`
### Parameters
- **listener** (TcpListener) - The TCP listener to bind the router to.
- **router** (Router) - The Topcoat router instance to serve.
### Errors
Returns `Err` if accepting or handling a connection on `listener` fails.
```
--------------------------------
### Get Zero-Indexed Number from Sunday
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/enum.Weekday.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Returns the zero-indexed position of the day starting from Sunday.
```rust
assert_eq!(Weekday::Monday.number_days_from_sunday(), 1);
```
--------------------------------
### Get Zero-Indexed Number from Monday
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/enum.Weekday.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Returns the zero-indexed position of the day starting from Monday.
```rust
assert_eq!(Weekday::Monday.number_days_from_monday(), 0);
```
--------------------------------
### Get One-Indexed Number from Sunday
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/enum.Weekday.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Returns the one-indexed position of the day starting from Sunday.
```rust
assert_eq!(Weekday::Monday.number_from_sunday(), 2);
```
--------------------------------
### Initialize a Topcoat application
Source: https://docs.rs/topcoat/0.1.3/topcoat/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Basic setup for a Topcoat application using the router and a simple component.
```rust
use topcoat::{
Result,
router::{Router, RouterBuilderDiscoverExt, page},
view::{component, view},
};
#[tokio::main]
async fn main() {
topcoat::start(Router::builder().discover().build()).await.unwrap();
}
#[page("/")]
async fn home() -> Result {
view! {
hello(name: "World")
}
}
#[component]
async fn hello(name: &str) -> Result {
view! {
"Hello, " (name) "!"
}
}
```
--------------------------------
### Get One-Indexed Number from Monday
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/enum.Weekday.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Returns the one-indexed position of the day starting from Monday.
```rust
assert_eq!(Weekday::Monday.number_from_monday(), 1);
```
--------------------------------
### Configuring font display and host
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/fontsource/macro.fontsource_font.html?search=std%3A%3Avec
Examples demonstrating how to set the font display strategy and the hosting source.
```rust
fontsource_font!(ROBOTO, display: Optional)
```
```rust
fontsource_font!(ROBOTO, host: Asset)
```
--------------------------------
### Get Date Monday-Based Week
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the week number where week 1 begins on the first Monday.
```rust
assert_eq!(date!(2019-01-01).monday_based_week(), 0);
assert_eq!(date!(2020-01-01).monday_based_week(), 0);
assert_eq!(date!(2020-12-31).monday_based_week(), 52);
assert_eq!(date!(2021-01-01).monday_based_week(), 0);
```
--------------------------------
### Get Date Sunday-Based Week
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Example of retrieving the week number where week 1 begins on the first Sunday.
```rust
assert_eq!(date!(2019-01-01).sunday_based_week(), 0);
assert_eq!(date!(2020-01-01).sunday_based_week(), 0);
assert_eq!(date!(2020-12-31).sunday_based_week(), 52);
assert_eq!(date!(2021-01-01).sunday_based_week(), 0);
```
--------------------------------
### Get a range of raw pointers for a slice
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Returns a half-open range of pointers. Useful for interoperability with C++ APIs that expect start and end pointers.
```rust
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;
assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
```
--------------------------------
### Start a Topcoat router
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.start.html
Initializes the router using the configured host and port from environment variables.
```rust
pub async fn start(router: Router) -> Result<(), Error>
```
--------------------------------
### Slice Length Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the len method on a slice.
```rust
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
```
--------------------------------
### topcoat::start
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/index.html?search=u32+-%3E+bool
Starts the Topcoat server using the provided router configuration. It binds to the host and port specified by environment variables or defaults to 127.0.0.1:3000.
```APIDOC
## topcoat::start(router: Router)
### Description
Starts the server with the provided router configuration. This function is typically awaited in the main entry point of the application.
### Parameters
- **router** (Router) - The configured router instance to serve.
### Example
```rust
#[tokio::main]
async fn main() {
let router = my_app::router();
topcoat::start(router).await.unwrap();
}
```
```
--------------------------------
### Slice Last Chunk Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the last_chunk method on a 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>());
```
--------------------------------
### Slice Last Element Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the last method on a slice.
```rust
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());
let w: &[i32] = &[];
assert_eq!(None, w.last());
```
--------------------------------
### Slice Split Last Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the split_last method on a slice.
```rust
let x = &[0, 1, 2];
if let Some((last, elements)) = x.split_last() {
assert_eq!(last, &2);
assert_eq!(elements, &[0, 1]);
}
```
--------------------------------
### Create HxLocation instances
Source: https://docs.rs/topcoat/0.1.3/topcoat/htmx/struct.HxLocation.html
Examples of creating a simple HxLocation and a detailed one with options.
```rust
use topcoat::htmx::{HxLocation, SwapOption};
// Plain path: `HX-Location: /home`
let simple = HxLocation::new("/home");
// With options, serialized as JSON.
let detailed = HxLocation::new("/home")
.target("#main")
.swap(SwapOption::InnerHtml);
```
--------------------------------
### pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.serve.html?search=u32+-%3E+bool
Serves a Topcoat router and notifies the dev server that the application is ready.
```APIDOC
## serve
### Description
Serve a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections. This calls `crate::dev::notify_ready` before handing the listener off to the router’s accept loop.
### Signature
`pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>`
### Errors
Returns `Err` if accepting or handling a connection on `listener` fails.
```
--------------------------------
### pub async fn serve
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.serve.html
Serves a Topcoat router and notifies the dev server of readiness.
```APIDOC
## pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>
### Description
Serve a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections. This calls `crate::dev::notify_ready` before handing the listener off to the router’s accept loop.
### Parameters
- **listener** (TcpListener) - The TCP listener to bind the router to.
- **router** (Router) - The Topcoat router instance to serve.
### Errors
Returns `Err` if accepting or handling a connection on `listener` fails.
```
--------------------------------
### Slice Emptiness Check Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the is_empty method on a slice.
```rust
let a = [1, 2, 3];
assert!(!a.is_empty());
let b: &[i32] = &[];
assert!(b.is_empty());
```
--------------------------------
### Run development build
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/index.html?search=
Initiates the development build process to bundle assets.
```bash
topcoat dev
# or
cargo topcoat dev
```
--------------------------------
### Slice Split Last Chunk Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the split_last_chunk method on a slice.
```rust
let x = &[0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk::<2>() {
assert_eq!(elements, &[0]);
assert_eq!(last, &[1, 2]);
}
assert_eq!(None, x.split_last_chunk::<4>());
```
--------------------------------
### Authenticate and start a session
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/index.html?search=
Use session::start to generate a fresh token after verifying user credentials.
```rust
use topcoat::{
Result,
context::Cx,
router::{SeeOther, route, see_other},
session,
};
#[route(POST "/login")]
async fn login(cx: &Cx) -> Result {
let user = verify_credentials(cx).await?;
let session = session::start(cx).await?;
persist_session(cx, &user, &session).await?;
Ok(see_other("/"))
}
```
--------------------------------
### Bundle assets via CLI
Source: https://docs.rs/topcoat/0.1.3/topcoat/tailwind/index.html?search=u32+-%3E+bool
Execute the asset bundling command for manual builds.
```bash
topcoat asset bundle
```
--------------------------------
### Slice Split First Chunk Example
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.FontFaces.html?search=std%3A%3Avec
Example usage of the split_first_chunk method on a slice.
```rust
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk::<2>() {
assert_eq!(first, &[0, 1]);
assert_eq!(elements, &[2]);
}
assert_eq!(None, x.split_first_chunk::<4>());
```
--------------------------------
### pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>
Source: https://docs.rs/topcoat/0.1.3/topcoat/fn.serve.html?search=std%3A%3Avec
Serves a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections. This function calls crate::dev::notify_ready before handing the listener off to the router’s accept loop.
```APIDOC
## serve
### Description
Serves a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections. This function calls `crate::dev::notify_ready` before handing the listener off to the router’s accept loop.
### Signature
`pub async fn serve(listener: TcpListener, router: Router) -> Result<(), Error>`
### Parameters
- **listener** (TcpListener) - The TCP listener to accept connections on.
- **router** (Router) - The Topcoat router to serve.
### Returns
- **Result<(), Error>** - Returns `Ok(())` on success, or `Err` if accepting or handling a connection on the listener fails.
```
--------------------------------
### is_leap_year Usage Examples
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/util/fn.is_leap_year.html?search=
Examples demonstrating leap year validation for various years.
```rust
assert!(!is_leap_year(1900));
assert!(is_leap_year(2000));
assert!(is_leap_year(2004));
assert!(!is_leap_year(2005));
assert!(!is_leap_year(2100));
```
--------------------------------
### Formatting with Iso8601
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/format_description/well_known/iso8601/struct.Iso8601.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Example demonstrating how to format a datetime using the default Iso8601 configuration.
```rust
assert_eq!(
datetime!(1997-11-12 9:55:06 -6:00).format(&Iso8601::DEFAULT)?,
"1997-11-12T09:55:06.000000000-06:00"
);
```
--------------------------------
### UnicodeRange::new
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.UnicodeRange.html
Creates an inclusive range from a start to an end UnicodeCodePoint. Panics if the end is before the start.
```APIDOC
## pub const fn new(start: UnicodeCodePoint, end: UnicodeCodePoint) -> UnicodeRange
### Description
Create an inclusive range from `start` to `end`.
### Panics
Panics if `end` is before `start`.
```
--------------------------------
### Retrieving App Context
Source: https://docs.rs/topcoat/0.1.3/topcoat/context/fn.try_app_context.html?search=std%3A%3Avec
Example demonstrating how to retrieve a custom configuration struct from the application context.
```rust
use topcoat::context::{Cx, try_app_context};
struct FeatureConfig;
fn feature_config(cx: &Cx) -> Option<&FeatureConfig> {
try_app_context(cx)
}
```
--------------------------------
### Example Search Queries
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/error/enum.TryFromParsed.html?search=
Common search patterns for finding types and trait implementations.
```text
std::vec
```
```text
u32 -> bool
```
```text
Option, (T -> U) -> Option
```
--------------------------------
### Rendered asset URL example
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/index.html?search=
Example of how an Asset ID renders as a hashed URL within the view.
```html
```
--------------------------------
### topcoat::session::start
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/fn.start.html?search=u32+-%3E+bool
Starts a new session, issuing a fresh token to the client. This function should be used to generate a new token, which should then be recorded in the application's session storage.
```APIDOC
## Function: start
### Description
Starts a new session, issuing a fresh token to the client. Always generates a new token (never reuses one the request presented), so calling this on login also protects against session fixation. Record the returned `Session` in the application’s session storage.
### Signature
`pub async fn start(cx: &Cx) -> Result`
### Parameters
- **cx** (&Cx) - The context required to start the session.
### Returns
- **Result** - Returns a `Session` object on success, or an `Error` if the token store fails to issue the token.
```
--------------------------------
### ObliqueAngleRange::new
Source: https://docs.rs/topcoat/0.1.3/topcoat/font/struct.ObliqueAngleRange.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Creates an inclusive range from a start and end ObliqueAngle. Panics if the end angle is before the start angle.
```APIDOC
## pub const fn new(start: ObliqueAngle, end: ObliqueAngle) -> ObliqueAngleRange
### Description
Creates an inclusive range from `start` to `end`.
### Panics
Panics if `end` is before `start`.
```
--------------------------------
### Building a Router with RouterBuilder
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.RouterBuilder.html?search=
Demonstrates configuring a router using discovery, cookies, assets, and application context before calling build.
```rust
use topcoat::{
asset::{AssetBundle, RouterBuilderAssetExt},
cookie::RouterBuilderCookieExt,
router::{Router, RouterBuilderDiscoverExt},
};
pub fn router() -> Router {
Router::builder()
.discover()
.cookies()
.assets(AssetBundle::load().unwrap())
.app_context(AppConfig::load())
.build()
}
```
--------------------------------
### Box Error Conversion Examples
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/type.BoxError.html?search=std%3A%3Avec
Examples demonstrating how to convert custom error types and strings into boxed error types.
```rust
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
let an_error = AnError;
assert!(0 == size_of_val(&an_error));
let a_boxed_error = Box::::from(an_error);
assert!(size_of::>() == size_of_val(&a_boxed_error))
```
```rust
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct AnError;
impl fmt::Display for AnError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error")
}
}
impl Error for AnError {}
unsafe impl Send for AnError {}
unsafe impl Sync for AnError {}
let an_error = AnError;
assert!(0 == size_of_val(&an_error));
let a_boxed_error = Box::::from(an_error);
assert!(
size_of::>() == size_of_val(&a_boxed_error))
```
```rust
use std::error::Error;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::::from(a_string_error);
assert!(size_of::>() == size_of_val(&a_boxed_error))
```
```rust
use std::error::Error;
let a_string_error = "a string error".to_string();
let a_boxed_error = Box::::from(a_string_error);
assert!(
size_of::>() == size_of_val(&a_boxed_error))
```
--------------------------------
### Create HxResponseTrigger Examples
Source: https://docs.rs/topcoat/0.1.3/topcoat/htmx/struct.HxResponseTrigger.html
Demonstrates creating simple event triggers and detailed JSON-serialized events for specific HTMX lifecycle stages.
```rust
use topcoat::htmx::{HxEvent, HxResponseTrigger};
// `HX-Trigger: refresh, close-modal`
let simple = HxResponseTrigger::receive(["refresh", "close-modal"]);
// JSON form, fired after the swap step.
let detailed =
HxResponseTrigger::after_swap([HxEvent::with_data("show-toast", "Saved!").unwrap()]);
```
--------------------------------
### Create and inspect a Path
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.Path.html
Demonstrates creating a Path from a string slice and verifying its segments and matchit-compatible representation.
```rust
use topcoat_router::Path;
let path = Path::new("/users/(group)/{id}");
assert_eq!(path.segments().count(), 3);
assert_eq!(path.to_matchit_path(), "/users/{id}");
```
--------------------------------
### new
Source: https://docs.rs/topcoat/0.1.3/topcoat/tailwind/struct.Executable.html?search=u32+-%3E+bool
Creates a new Executable instance. A bare command name like 'tailwindcss' is resolved through the system PATH when run.
```APIDOC
## pub fn new(path: impl Into) -> Executable
### Description
Creates a new instance of an Executable at the specified path. If a bare command name is provided, it will be resolved via the system PATH.
### Parameters
- **path** (impl Into) - Required - The path to the executable or the command name.
```
--------------------------------
### Initialize a Cookie Store
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/fn.cookie_store.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Example of creating a cookie store for a 'cart' cookie and parsing it or falling back to a default value.
```rust
let cart = cookie_store::(private_cookies(cx), "cart").parse_or_default();
```
--------------------------------
### pub fn matches_start(&self, url: &str) -> bool
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.Path.html
Checks if a concrete URL path starts with the route path, allowing for additional trailing segments.
```APIDOC
## pub fn matches_start(&self, url: &str) -> bool
### Description
Returns true if the provided URL path starts with this route path. This method allows for trailing URL segments beyond the defined path, useful for layout selection.
### Parameters
- **url** (str) - Required - The concrete URL path to check.
```
--------------------------------
### Initialize Router
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/macro.module_router.html
Call the macro from the root module to build the router.
```rust
// src/app.rs
pub fn router() -> topcoat::router::Router {
topcoat::router::module_router!().build()
}
```
--------------------------------
### Initialize CookieTokenStore
Source: https://docs.rs/topcoat/0.1.3/topcoat/session/cookie/struct.CookieTokenStore.html?search=
Methods for creating and configuring a new CookieTokenStore instance.
```rust
pub fn new() -> CookieTokenStore
```
```rust
pub fn name(self, name: impl Into>) -> CookieTokenStore
```
--------------------------------
### truncate_to_day
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.OffsetDateTime.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Truncate the time to the start of the day.
```APIDOC
## pub const fn truncate_to_day(self) -> OffsetDateTime
### Description
Truncates the OffsetDateTime to the start of the day, effectively setting the time component to midnight.
```
--------------------------------
### View Implementation Methods
Source: https://docs.rs/topcoat/0.1.3/topcoat/view/struct.View.html?search=
Methods for creating and rendering View instances.
```rust
pub fn empty() -> View
```
```rust
pub const fn unescaped_unchecked(body: &'static str) -> View
```
```rust
pub fn render(&self, cx: &Cx) -> String
```
```rust
pub fn render_response(&self, cx: &Cx) -> RenderedResponse
```
--------------------------------
### get
Source: https://docs.rs/topcoat/0.1.3/topcoat/runtime/struct.SignalSurrogate.html?search=
Retrieves the value from the signal surrogate.
```APIDOC
## pub fn get(&self) -> ::Surrogate
### Description
Retrieves the value from the signal surrogate.
### Signature
`pub fn get(&self) -> ::Surrogate`
```
--------------------------------
### Using HTTP Method constants and utilities
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.Method.html
Demonstrates creating a Method from bytes and checking its properties.
```rust
use http::Method;
assert_eq!(Method::GET, Method::from_bytes(b"GET").unwrap());
assert!(Method::GET.is_idempotent());
assert_eq!(Method::POST.as_str(), "POST");
```
--------------------------------
### get
Source: https://docs.rs/topcoat/0.1.3/topcoat/runtime/struct.SignalSurrogate.html
Retrieves the surrogate value from the signal.
```APIDOC
## pub fn get(&self) -> ::Surrogate
### Description
Retrieves the surrogate value from the signal. This method is available when `T` implements `Surrogated` and `Clone`.
```
--------------------------------
### Construct AssetOptions using asset_options macro
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/macro.asset_options.html
Example of building an AssetOptions instance with specific field values.
```rust
use topcoat_asset::{AssetOptions, asset_options};
const OPTS: AssetOptions = asset_options!(rename: "primary", extension: "woff2");
```
--------------------------------
### Get Weekday
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.Date.html?search=
Returns the weekday of the date.
```rust
assert_eq!(date!(2019-01-01).weekday(), Tuesday);
assert_eq!(date!(2019-02-01).weekday(), Friday);
assert_eq!(date!(2019-03-01).weekday(), Friday);
assert_eq!(date!(2019-04-01).weekday(), Monday);
assert_eq!(date!(2019-05-01).weekday(), Wednesday);
assert_eq!(date!(2019-06-01).weekday(), Saturday);
assert_eq!(date!(2019-07-01).weekday(), Monday);
assert_eq!(date!(2019-08-01).weekday(), Thursday);
assert_eq!(date!(2019-09-01).weekday(), Sunday);
assert_eq!(date!(2019-10-01).weekday(), Tuesday);
assert_eq!(date!(2019-11-01).weekday(), Friday);
assert_eq!(date!(2019-12-01).weekday(), Sunday);
```
--------------------------------
### BuildConfig::new
Source: https://docs.rs/topcoat/0.1.3/topcoat/tailwind/struct.BuildConfig.html
Creates a new instance of BuildConfig with default settings.
```APIDOC
## pub fn new() -> BuildConfig
### Description
Initializes a new BuildConfig instance, ready to be customized with builder methods and executed with `render`.
### Returns
- **BuildConfig** - A new configuration instance.
```
--------------------------------
### serve
Source: https://docs.rs/topcoat/0.1.3/topcoat/index.html
Serve a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections.
```APIDOC
## serve
### Description
Serve a Topcoat router, notifying the topcoat dev server once the application is ready to accept connections.
```
--------------------------------
### get
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/struct.CookieJar.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Retrieves a cookie by name from the jar.
```APIDOC
## fn get(&self, name: &str) -> Option>
### Description
Returns the cookie named `name`, or `None` if it is absent (or, for signed/encrypted jars, fails to verify).
```
--------------------------------
### Constructing Box from raw pointers
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/type.BoxError.html?search=std%3A%3Avec
Examples demonstrating how to recreate a Box from a raw pointer or manually allocate memory for a Box using the system allocator.
```rust
#![feature(allocator_api)]
use std::alloc::System;
let x = Box::new_in(5, System);
let (ptr, alloc) = Box::into_raw_with_allocator(x);
let x = unsafe { Box::from_raw_in(ptr, alloc) };
```
```rust
#![feature(allocator_api, slice_ptr_get)]
use std::alloc::{Allocator, Layout, System};
unsafe {
let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32;
// In general .write is required to avoid attempting to destruct
// the (uninitialized) previous contents of `ptr`, though for this
// simple example `*ptr = 5` would have worked as well.
ptr.write(5);
let x = Box::from_raw_in(ptr, System);
}
```
--------------------------------
### get
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/header/struct.HeaderMap.html
Returns a reference to the value associated with the key.
```APIDOC
## pub fn get(&self, key: K) -> Option<&T>
### Description
Returns a reference to the value associated with the key. If multiple values exist, the first one is returned.
```
--------------------------------
### Executable::new
Source: https://docs.rs/topcoat/0.1.3/topcoat/tailwind/struct.Executable.html
Creates a new Executable instance from a given path. If a bare command name is provided, it is resolved through the system PATH.
```APIDOC
## pub fn new(path: impl Into) -> Executable
### Description
Creates a new Tailwind CLI executable instance. If a bare command name like "tailwindcss" is provided, it will be resolved through the system PATH when executed.
### Parameters
- **path** (impl Into) - Required - The path to the executable or the command name.
```
--------------------------------
### Get Year Component
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.UtcDateTime.html
Retrieves the year as an i32.
```rust
assert_eq!(utc_datetime!(2019-01-01 0:00).year(), 2019);
assert_eq!(utc_datetime!(2019-12-31 0:00).year(), 2019);
assert_eq!(utc_datetime!(2020-01-01 0:00).year(), 2020);
```
--------------------------------
### Accessing Uri Query Components
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/struct.Uri.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Examples demonstrating how to retrieve or verify the query string component of a Uri.
```rust
assert_eq!(uri.query(), Some("key=value&foo=bar"));
```
```rust
let uri: Uri = "/hello/world".parse().unwrap();
assert!(uri.query().is_none());
```
--------------------------------
### Get UtcOffset
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.OffsetDateTime.html
Retrieves the UtcOffset associated with the OffsetDateTime.
```rust
assert_eq!(datetime!(2019-01-01 0:00 UTC).offset(), offset!(UTC));
assert_eq!(datetime!(2019-01-01 0:00 +1).offset(), offset!(+1));
```
--------------------------------
### pub fn load(path: impl AsRef) -> Result
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/struct.Manifest.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E
Reads and parses a manifest from the specified path, rejecting unsupported versions.
```APIDOC
## pub fn load(path: impl AsRef) -> Result
### Description
Read and parse a manifest from a file path, rejecting unsupported versions. Returns an error if the file is not valid TOML, if the version field is incorrect, or if an I/O error occurs.
### Parameters
- **path** (impl AsRef) - Required - The file path to the manifest file.
```
--------------------------------
### Get cookie name
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/struct.Cookie.html
Retrieves the name of the cookie.
```rust
use cookie::Cookie;
let c = Cookie::new("name", "value");
assert_eq!(c.name(), "name");
```
--------------------------------
### Basic class! macro usage
Source: https://docs.rs/topcoat/0.1.3/topcoat/view/macro.class.html
Demonstrates building a class list with static strings and a simple conditional.
```rust
use topcoat::view::{class, view};
let is_active = true;
view! {
}
```
--------------------------------
### Truncate to Day
Source: https://docs.rs/topcoat/0.1.3/topcoat/cookie/time/struct.PrimitiveDateTime.html?search=
Truncates the time to the start of the day (midnight).
```rust
assert_eq!(
datetime!(2022-02-18 15:30:45.123_456_789).truncate_to_day(),
datetime!(2022-02-18 0:00)
);
```
--------------------------------
### Request Builder Usage
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/type.Request.html?search=
Examples of using the Request builder and various HTTP method initializers.
```rust
let request = Request::builder()
.method("GET")
.uri("https://www.rust-lang.org/")
.header("X-Custom-Foo", "Bar")
.body(())
.unwrap();
```
```rust
let request = Request::get("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::put("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::post("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::delete("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::options("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::head("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::connect("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::patch("https://www.rust-lang.org/")
.body(())
.unwrap();
```
```rust
let request = Request::trace("https://www.rust-lang.org/")
.body(())
.unwrap();
```
--------------------------------
### Load asset bundle at runtime
Source: https://docs.rs/topcoat/0.1.3/topcoat/tailwind/index.html?search=u32+-%3E+bool
Register the asset bundle with the router during application startup.
```rust
use topcoat::{
asset::{AssetBundle, RouterBuilderAssetExt},
router::{Router, RouterBuilderDiscoverExt},
};
let router = Router::builder()
.discover()
.assets(AssetBundle::load_dir("target/assets").unwrap())
.build();
```
--------------------------------
### Define Page Handler
Source: https://docs.rs/topcoat/0.1.3/topcoat/router/macro.module_router.html
Example of a page handler in a submodule.
```rust
// src/app/about.rs: page at "/about"
#[page]
async fn about() -> Result {
view! {
"About"
}
}
```
--------------------------------
### Get Procedure ID
Source: https://docs.rs/topcoat/0.1.3/topcoat/runtime/struct.Procedure.html
Retrieves the unique identifier for the procedure.
```rust
pub fn id(&self) -> ProcedureId
```
--------------------------------
### Manifest::load
Source: https://docs.rs/topcoat/0.1.3/topcoat/asset/struct.Manifest.html?search=u32+-%3E+bool
Reads and parses a manifest file from the specified path, rejecting unsupported versions.
```APIDOC
## pub fn load(path: impl AsRef) -> Result
### Description
Reads and parses a manifest from the provided path. It validates the file format and version, returning an error if the file is invalid or the version is unsupported.
### Parameters
- **path** (impl AsRef) - Required - The file system path to the manifest file.
### Returns
- **Result** - Returns the parsed Manifest instance on success, or an Error if the file cannot be read or parsed.
```