Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

The main client for interacting with the Google Generative AI API.

Implementations§

Source§

impl Client

Source

pub const fn builder(api_key: String) -> ClientBuilder

Creates a new builder for Client instances.

§Arguments
  • api_key - Your Google AI API key.
Source

pub fn new(api_key: String) -> Self

Creates a new GenAI client.

§Arguments
  • api_key - Your Google AI API key.
Source

pub fn interaction(&self) -> InteractionBuilder<'_>

Creates a builder for constructing an interaction request.

This provides a fluent interface for building interactions with models or agents. Use this method for a more ergonomic API compared to manually constructing InteractionRequest.

§Examples
let client = Client::builder("api_key".to_string()).build()?;

// Simple interaction
let response = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_text("Hello, world!")
    .create()
    .await?;

// Stateful conversation (requires stored interaction)
let response2 = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_text("What did I just say?")
    .with_previous_interaction(response.id.as_ref().expect("stored interaction has id"))
    .create()
    .await?;
Source

pub async fn execute( &self, request: InteractionRequest, ) -> Result<InteractionResponse, GenaiError>

Creates a new interaction using the Gemini Interactions API.

The Interactions API provides a unified interface for working with models and agents, with built-in support for stateful conversations, function calling, and long-running tasks.

§Arguments
  • request - The interaction request with model/agent, input, and optional configuration.
§Errors

Returns an error if:

  • The HTTP request fails
  • Response parsing fails
  • The API returns an error
§Example
use genai_rs::Client;
use genai_rs::{InteractionRequest, InteractionInput};

let client = Client::new("your-api-key".to_string());

let request = InteractionRequest {
    model: Some("gemini-3-flash-preview".to_string()),
    agent: None,
    agent_config: None,
    input: InteractionInput::Text("Hello, world!".to_string()),
    previous_interaction_id: None,
    tools: None,
    response_modalities: None,
    response_format: None,
    response_mime_type: None,
    generation_config: None,
    stream: None,
    background: None,
    store: None,
    system_instruction: None,
};

let response = client.execute(request).await?;
println!("Interaction ID: {:?}", response.id);
§Streaming Example
use genai_rs::{Client, StreamChunk};
use genai_rs::{InteractionRequest, InteractionInput};
use futures_util::StreamExt;

let client = Client::builder("api_key".to_string()).build()?;
let request = InteractionRequest {
    model: Some("gemini-3-flash-preview".to_string()),
    agent: None,
    agent_config: None,
    input: InteractionInput::Text("Count to 5".to_string()),
    previous_interaction_id: None,
    tools: None,
    response_modalities: None,
    response_format: None,
    response_mime_type: None,
    generation_config: None,
    stream: Some(true),
    background: None,
    store: None,
    system_instruction: None,
};

let mut last_event_id = None;
let mut stream = client.execute_stream(request);
while let Some(result) = stream.next().await {
    let event = result?;
    last_event_id = event.event_id.clone();  // Track for resume
    match event.chunk {
        StreamChunk::Delta(delta) => {
            if let Some(text) = delta.as_text() {
                print!("{}", text);
            }
        }
        StreamChunk::Complete(response) => {
            println!("\nDone! ID: {:?}", response.id);
        }
        _ => {} // Handle unknown future variants
    }
}
§Retry Example
use genai_rs::Client;
use std::time::Duration;

let client = Client::new("api_key".to_string());
let request = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_text("Hello!")
    .build()?;

// Retry loop with exponential backoff
let mut attempts = 0;
let response = loop {
    match client.execute(request.clone()).await {
        Ok(r) => break r,
        Err(e) if e.is_retryable() && attempts < 3 => {
            attempts += 1;
            tokio::time::sleep(Duration::from_millis(100 * 2u64.pow(attempts))).await;
        }
        Err(e) => return Err(e.into()),
    }
};
Source

pub fn execute_stream( &self, request: InteractionRequest, ) -> BoxStream<'_, Result<StreamEvent, GenaiError>>

Executes a pre-built interaction request with streaming.

This is the streaming variant of execute().

Returns a stream of StreamEvent items as they arrive. Each event contains:

  • chunk: The content (delta or complete response)
  • event_id: Optional ID for resuming interrupted streams
§Example
use genai_rs::{Client, StreamChunk};
use futures_util::StreamExt;

let client = Client::new("api_key".to_string());

let request = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_text("Count to 5")
    .build()?;

let mut stream = client.execute_stream(request);
while let Some(result) = stream.next().await {
    let event = result?;
    match event.chunk {
        StreamChunk::Delta(delta) => {
            if let Some(text) = delta.as_text() {
                print!("{}", text);
            }
        }
        StreamChunk::Complete(response) => {
            println!("\nDone!");
        }
        _ => {}
    }
}
Source

pub async fn get_interaction( &self, interaction_id: &str, ) -> Result<InteractionResponse, GenaiError>

Retrieves an existing interaction by its ID.

Useful for checking the status of long-running interactions or agents, or for retrieving the full conversation history.

§Arguments
  • interaction_id - The unique identifier of the interaction to retrieve.
§Errors

Returns an error if:

  • The HTTP request fails
  • Response parsing fails
  • The API returns an error
Source

pub fn get_interaction_stream<'a>( &'a self, interaction_id: &'a str, last_event_id: Option<&'a str>, ) -> BoxStream<'a, Result<StreamEvent, GenaiError>>

Retrieves an existing interaction by its ID with streaming.

Returns a stream of events for the interaction. This is useful for:

  • Resuming an interrupted stream using last_event_id
  • Streaming a long-running interaction’s progress (e.g., deep research)

Each event includes an event_id that can be used to resume the stream from that point if the connection is interrupted.

§Arguments
  • interaction_id - The unique identifier of the interaction to stream.
  • last_event_id - Optional event ID to resume from. Pass the last received event’s event_id to continue from where you left off.
§Returns

A boxed stream that yields StreamEvent items.

§Example
use genai_rs::{Client, StreamChunk};
use futures_util::StreamExt;

let client = Client::builder("api_key".to_string()).build()?;
let interaction_id = "some-interaction-id";

// Resume a stream from a previous event
let last_event_id = Some("evt_abc123");
let mut stream = client.get_interaction_stream(interaction_id, last_event_id);

while let Some(result) = stream.next().await {
    let event = result?;
    println!("Event ID: {:?}", event.event_id);
    match event.chunk {
        StreamChunk::Delta(delta) => {
            if let Some(text) = delta.as_text() {
                print!("{}", text);
            }
        }
        StreamChunk::Complete(response) => {
            println!("\nDone! Status: {:?}", response.status);
        }
        _ => {}
    }
}
Source

pub async fn delete_interaction( &self, interaction_id: &str, ) -> Result<(), GenaiError>

Deletes an interaction by its ID.

Removes the interaction from the server, freeing up storage and making it unavailable for future reference via previous_interaction_id.

§Arguments
  • interaction_id - The unique identifier of the interaction to delete.
§Errors

Returns an error if:

  • The HTTP request fails
  • The API returns an error
Source

pub async fn cancel_interaction( &self, interaction_id: &str, ) -> Result<InteractionResponse, GenaiError>

Cancels an in-progress background interaction.

Only applicable to interactions created with background: true that are still in InProgress status. Returns the updated interaction with status Cancelled.

This is useful for:

  • Halting long-running agent tasks (e.g., deep-research) when requirements change
  • Cost control by stopping interactions consuming significant tokens
  • Implementing timeout handling in application logic
  • Supporting user-initiated cancellation in UIs
§Arguments
  • interaction_id - The unique identifier of the interaction to cancel.
§Errors

Returns an error if:

  • The interaction doesn’t exist
  • The interaction is not in a cancellable state (not background or already complete)
  • The HTTP request fails
  • The API returns an error
§Example
use genai_rs::{Client, InteractionStatus};

let client = Client::new("your-api-key".to_string());

// Start a background agent interaction
let response = client.interaction()
    .with_agent("deep-research-pro-preview-12-2025")
    .with_text("Research AI safety")
    .with_background(true)
    .with_store_enabled()
    .create()
    .await?;

let interaction_id = response.id.as_ref().expect("stored interaction has id");

// Later, cancel if still in progress
if response.status == InteractionStatus::InProgress {
    let cancelled = client.cancel_interaction(interaction_id).await?;
    assert_eq!(cancelled.status, InteractionStatus::Cancelled);
    println!("Interaction cancelled");
}
Source

pub async fn upload_file( &self, path: impl AsRef<Path>, ) -> Result<FileMetadata, GenaiError>

Uploads a file from a path to the Files API.

Files are stored for 48 hours and can be referenced in interactions by their URI. This is more efficient than inline base64 encoding for large files or files that will be used across multiple interactions.

§Arguments
  • path - Path to the file to upload
§Errors

Returns an error if:

  • The file cannot be read
  • The MIME type cannot be determined
  • The upload fails
§Example
use genai_rs::{Client, Content};

let client = Client::new("api-key".to_string());

// Upload a video file
let file = client.upload_file("video.mp4").await?;
println!("Uploaded: {} -> {}", file.name, file.uri);

// Use in interaction
let response = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_content(vec![
        Content::text("Describe this video"),
        Content::from_file(&file),
    ])
    .create()
    .await?;
Source

pub async fn upload_file_with_mime( &self, path: impl AsRef<Path>, mime_type: &str, ) -> Result<FileMetadata, GenaiError>

Uploads a file with an explicit MIME type.

Use this when automatic MIME type detection isn’t suitable.

§Arguments
  • path - Path to the file to upload
  • mime_type - MIME type of the file (e.g., “video/mp4”)
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

let file = client.upload_file_with_mime("data.bin", "application/octet-stream").await?;
Source

pub async fn upload_file_bytes( &self, data: Vec<u8>, mime_type: &str, display_name: Option<&str>, ) -> Result<FileMetadata, GenaiError>

Uploads file bytes directly with a specified MIME type.

Use this when you already have file contents in memory.

§Arguments
  • data - File contents as bytes
  • mime_type - MIME type of the file
  • display_name - Optional display name for the file
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

// Upload bytes from memory
let video_bytes = std::fs::read("video.mp4")?;
let file = client.upload_file_bytes(video_bytes, "video/mp4", Some("my-video")).await?;
Source

pub async fn get_file( &self, file_name: &str, ) -> Result<FileMetadata, GenaiError>

Gets metadata for an uploaded file.

Use this to check the processing status of a recently uploaded file.

§Arguments
  • file_name - The resource name of the file (e.g., “files/abc123”)
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

let file = client.get_file("files/abc123").await?;
if file.is_active() {
    println!("File is ready to use");
} else if file.is_processing() {
    println!("File is still processing...");
}
Source

pub async fn list_files( &self, page_size: Option<u32>, page_token: Option<&str>, ) -> Result<ListFilesResponse, GenaiError>

Lists all uploaded files.

§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

let response = client.list_files(None, None).await?;
for file in response.files {
    println!("{}: {} ({})", file.name, file.display_name.as_deref().unwrap_or(""), file.mime_type);
}
Source

pub async fn delete_file(&self, file_name: &str) -> Result<(), GenaiError>

Deletes an uploaded file.

§Arguments
  • file_name - The resource name of the file to delete (e.g., “files/abc123”)
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

// Upload, use, then delete
let file = client.upload_file("video.mp4").await?;
// ... use in interactions ...
client.delete_file(&file.name).await?;
Source

pub async fn upload_file_chunked( &self, path: impl AsRef<Path>, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>

Uploads a file using chunked transfer to minimize memory usage.

Unlike upload_file, this method streams the file from disk in chunks, never loading the entire file into memory. This is ideal for large files (500MB-2GB) or memory-constrained environments.

§Arguments
  • path - Path to the file to upload
§Returns

Returns a tuple of:

  • FileMetadata: The uploaded file’s metadata
  • ResumableUpload: A handle that can be used to resume if the upload is interrupted
§Memory Usage

This method uses approximately 8MB of memory for buffering, regardless of the file size. A 2GB file uses the same memory as a 10MB file.

§Errors

Returns an error if:

  • The file cannot be read
  • The MIME type cannot be determined
  • The upload fails
§Example
use genai_rs::{Client, Content};

let client = Client::new("api-key".to_string());

// Upload a large video file without loading it all into memory
let (file, _upload_handle) = client.upload_file_chunked("large_video.mp4").await?;
println!("Uploaded: {} -> {}", file.name, file.uri);

// Use in interaction
let response = client.interaction()
    .with_model("gemini-3-flash-preview")
    .with_content(vec![
        Content::text("Describe this video"),
        Content::from_file(&file),
    ])
    .create()
    .await?;
Source

pub async fn upload_file_chunked_with_mime( &self, path: impl AsRef<Path>, mime_type: &str, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>

Uploads a file using chunked transfer with an explicit MIME type.

Use this when automatic MIME type detection isn’t suitable.

§Arguments
  • path - Path to the file to upload
  • mime_type - MIME type of the file (e.g., “video/mp4”)
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

let (file, _) = client.upload_file_chunked_with_mime(
    "data.bin",
    "application/octet-stream"
).await?;
Source

pub async fn upload_file_chunked_with_options( &self, path: impl AsRef<Path>, mime_type: &str, chunk_size: usize, ) -> Result<(FileMetadata, ResumableUpload), GenaiError>

Uploads a file using chunked transfer with a custom chunk size.

This is the same as upload_file_chunked_with_mime but allows specifying the chunk size for streaming. Larger chunks are more efficient for fast networks, while smaller chunks use less memory.

§Arguments
  • path - Path to the file to upload
  • mime_type - MIME type of the file
  • chunk_size - Size of chunks to stream in bytes (default: 8MB)
§Example
use genai_rs::Client;

let client = Client::new("api-key".to_string());

// Use 16MB chunks for faster upload on a fast network
let chunk_size = 16 * 1024 * 1024;
let (file, _) = client.upload_file_chunked_with_options(
    "large_video.mp4",
    "video/mp4",
    chunk_size
).await?;
Source

pub async fn wait_for_file_ready( &self, file: &FileMetadata, poll_interval: Duration, timeout: Duration, ) -> Result<FileMetadata, GenaiError>

Waits for a file to finish processing.

Some files (especially videos) require processing before they can be used. This method polls the file status until it becomes active or fails.

§Arguments
  • file - The file metadata to wait for
  • poll_interval - How often to check the status
  • timeout - Maximum time to wait
§Returns

Returns the updated file metadata when processing completes.

§Errors

Returns an error if:

  • The file processing fails
  • The timeout is exceeded
§Example
use genai_rs::Client;
use std::time::Duration;

let client = Client::new("api-key".to_string());

let file = client.upload_file("large_video.mp4").await?;

// Wait for processing to complete
let ready_file = client.wait_for_file_ready(
    &file,
    Duration::from_secs(2),
    Duration::from_secs(120)
).await?;

println!("File ready: {}", ready_file.uri);

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Paint for T
where T: ?Sized,

Source§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
Source§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Primary].

§Example
println!("{}", value.primary());
Source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Fixed].

§Example
println!("{}", value.fixed(color));
Source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Rgb].

§Example
println!("{}", value.rgb(r, g, b));
Source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Black].

§Example
println!("{}", value.black());
Source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Red].

§Example
println!("{}", value.red());
Source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Green].

§Example
println!("{}", value.green());
Source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Yellow].

§Example
println!("{}", value.yellow());
Source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Blue].

§Example
println!("{}", value.blue());
Source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Magenta].

§Example
println!("{}", value.magenta());
Source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Cyan].

§Example
println!("{}", value.cyan());
Source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: White].

§Example
println!("{}", value.white());
Source§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlack].

§Example
println!("{}", value.bright_black());
Source§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightRed].

§Example
println!("{}", value.bright_red());
Source§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightGreen].

§Example
println!("{}", value.bright_green());
Source§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightYellow].

§Example
println!("{}", value.bright_yellow());
Source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlue].

§Example
println!("{}", value.bright_blue());
Source§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.bright_magenta());
Source§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightCyan].

§Example
println!("{}", value.bright_cyan());
Source§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightWhite].

§Example
println!("{}", value.bright_white());
Source§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
Source§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Primary].

§Example
println!("{}", value.on_primary());
Source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Fixed].

§Example
println!("{}", value.on_fixed(color));
Source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Rgb].

§Example
println!("{}", value.on_rgb(r, g, b));
Source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Black].

§Example
println!("{}", value.on_black());
Source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Red].

§Example
println!("{}", value.on_red());
Source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Green].

§Example
println!("{}", value.on_green());
Source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Yellow].

§Example
println!("{}", value.on_yellow());
Source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Blue].

§Example
println!("{}", value.on_blue());
Source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Magenta].

§Example
println!("{}", value.on_magenta());
Source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Cyan].

§Example
println!("{}", value.on_cyan());
Source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: White].

§Example
println!("{}", value.on_white());
Source§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlack].

§Example
println!("{}", value.on_bright_black());
Source§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightRed].

§Example
println!("{}", value.on_bright_red());
Source§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightGreen].

§Example
println!("{}", value.on_bright_green());
Source§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightYellow].

§Example
println!("{}", value.on_bright_yellow());
Source§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlue].

§Example
println!("{}", value.on_bright_blue());
Source§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.on_bright_magenta());
Source§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightCyan].

§Example
println!("{}", value.on_bright_cyan());
Source§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightWhite].

§Example
println!("{}", value.on_bright_white());
Source§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling Attribute value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
Source§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Bold].

§Example
println!("{}", value.bold());
Source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Dim].

§Example
println!("{}", value.dim());
Source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Italic].

§Example
println!("{}", value.italic());
Source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Underline].

§Example
println!("{}", value.underline());

Returns self with the attr() set to [Attribute :: Blink].

§Example
println!("{}", value.blink());

Returns self with the attr() set to [Attribute :: RapidBlink].

§Example
println!("{}", value.rapid_blink());
Source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Invert].

§Example
println!("{}", value.invert());
Source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Conceal].

§Example
println!("{}", value.conceal());
Source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Strike].

§Example
println!("{}", value.strike());
Source§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi Quirk value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
Source§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Mask].

§Example
println!("{}", value.mask());
Source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Wrap].

§Example
println!("{}", value.wrap());
Source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Linger].

§Example
println!("{}", value.linger());
Source§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to [Quirk :: Clear].

§Example
println!("{}", value.clear());
Source§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Resetting].

§Example
println!("{}", value.resetting());
Source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Bright].

§Example
println!("{}", value.bright());
Source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: OnBright].

§Example
println!("{}", value.on_bright());
Source§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the Condition value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
Source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
Source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more