### Busybox '--install' option example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/clap/examples/multicall-busybox.md Shows the usage of the '--install' option, which is useful for installing hardlinks for all subcommands. This example demonstrates a scenario where the main program takes arguments not directly related to applet subcommands. ```console $ busybox --install ? failed ... ``` -------------------------------- ### Basic HTTP Server Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/tiny_http/README.md A simple example demonstrating how to create an HTTP server, listen for incoming requests, and respond with 'hello world'. This snippet shows basic server setup and request handling. ```rust use tiny_http::{Server, Response}; let server = Server::http("0.0.0.0:8000").unwrap(); for request in server.incoming_requests() { println!("received request! method: {:?}, url: {:?}, headers: ?", request.method(), request.url(), request.headers() ); let response = Response::from_string("hello world"); request.respond(response); } ``` -------------------------------- ### Get and print OS information Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/os_info/README.md This example demonstrates how to get the operating system information using the os_info crate and print it in various formats. ```rust let info = os_info::get(); // Print full information: println!("OS information: {info}"); // Print information separately: println!("Type: {}", info.os_type()); println!("Version: {}", info.version()); println!("Bitness: {}", info.bitness()); println!("Architecture: {}", info.architecture()); ``` -------------------------------- ### Run Rustls mio server example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/rustls/README.md Demonstrates how to run the `tlsserver-mio` example program to start a TLS echo server. It shows how to connect to the server using `openssl` and `tlsclient-mio`. ```bash $ cargo run --bin tlsserver-mio -- --certs test-ca/rsa-2048/end.fullchain --key test-ca/rsa-2048/end.key -p 8443 echo & ``` ```bash $ echo hello world | openssl s_client -ign_eof -quiet -connect localhost:8443 ``` ```bash $ echo hello world | cargo run --bin tlsclient-mio -- --cafile test-ca/rsa-2048/ca.cert --port 8443 localhost ``` ```bash Run `cargo run --bin tlsserver-mio -- --help` for more options. ``` -------------------------------- ### Run Hostname Command Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/clap/examples/multicall-hostname.md This is an example of running the 'hostname' command. Without the necessary links setup, the multicall behavior cannot be fully demonstrated. ```console $ hostname www ``` -------------------------------- ### Run Server Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/hyper-rustls/README.md Execute the server example using Cargo. This command compiles and runs the server example provided by the crate. ```bash cargo run --example server ``` -------------------------------- ### Run Client Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/hyper-rustls/README.md Execute the client example with a specific URL using Cargo. This command compiles and runs the client example, passing a URL as an argument. ```bash cargo run --example client "https://docs.rs/hyper-rustls/latest/hyper_rustls/" ``` -------------------------------- ### Swift Usage Example Source: https://github.com/brave/brave-core/blob/master/docs/keyed_services.md Example of how to access the ExampleServiceFactory in Swift, potentially for private mode. ```swift ExampleServiceFactory.get(privateMode: privateMode), ``` -------------------------------- ### Install npm Dependencies Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/wasm-pack/RELEASE_CHECKLIST.md Navigate to the npm directory and install its dependencies. ```bash cd npm && npm install ``` -------------------------------- ### Run Quinn Examples Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/quinn/README.md Launch the example server and client applications. The server serves files from the current directory, and the client fetches a specified file. ```sh $ cargo run --example server ./ $ cargo run --example client https://localhost:4433/Cargo.toml ``` -------------------------------- ### Setup Dependencies Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/wasm-opt-sys/binaryen/README.md Install required dependencies such as SpiderMonkey JS shell, V8 JS shell, and WABT. Other scripts automatically detect these when installed. ```bash ./third_party/setup.py [mozjs|v8|wabt|all] ``` -------------------------------- ### Run Minimal Quinn Connection Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/quinn/examples/README.md Establishes a basic QUIC connection on localhost using the minimum amount of code. The server generates its own certificate for the client to trust. ```text $ cargo run --example connection ``` -------------------------------- ### Run Hyper Client Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating multipart usage with the hyper::client::Request API. ```bash $ cargo run --example hyper_client ``` -------------------------------- ### Run Verify Example Source: https://github.com/brave/brave-core/blob/master/third_party/rust/chromium_crates_io/vendor/bls-signatures-v0_15/README.md Verify 10,000 aggregated signatures by running the verify example with the release build. ```bash > cargo run --example verify --release ``` -------------------------------- ### Renderer class installation and methods Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/wsvn.com/original.html Defines the Renderer class, including its installation method, configuration retrieval, event handler setup, video event handling, and command processing. Useful for managing ad renderers. ```javascript u.install=function(e){return new u({url:e.url,config:e.config,id:e.id,callback:e.callback,loaded:e.loaded,adUnitCode:e.adUnitCode})},u.prototype.getConfig=function(){return this.config},u.prototype.setRender=function(e){this._render=e},u.prototype.setEventHandlers=function(e){this.handlers=e},u.prototype.handleVideoEvent=function(e){var t=e.id,n=e.eventName;"function"==typeof this.handlers[n]&&this.handlers[n](),(0,i.logMessage)("Prebid Renderer event for id ".concat(t," type ").concat(n))},u.prototype.process=function(){for(;this.cmd.length>0;)try{this.cmd.shift().call()}catch(e){(0,i.logError)("Error processing Renderer command: ",e)}}} ``` -------------------------------- ### Run Abscissa Application Subcommand Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/abscissa_core/README.md Execute a subcommand of a generated Abscissa application. This example shows how to run the 'start' subcommand. ```text cargo run -- start world ``` -------------------------------- ### Run Iron Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating multipart usage with the Iron web framework. Ensure the 'iron' feature is enabled. ```bash $ cargo run --features iron --example iron ``` -------------------------------- ### Get Pathname from URL Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/usathrill.com/original.html Extracts the pathname from a URL, optionally removing a base URL prefix. Ensures the pathname starts with a '/'. ```javascript function(e,t){var n=t?e.substring(this.config.siteUrl.length):e;return n.startsWith("/")||(n="/"+n),this._shouldAddTrailingSlash(n)?n+"/":n} ``` -------------------------------- ### Run Example from Command Line Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/iana-time-zone/README.md Demonstrates how to compile and run the `get_timezone` example provided with the crate using Cargo. ```bash cargo run --example get_timezone ``` -------------------------------- ### Run Rocket Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating how multipart's server API can be used with Rocket. Ensure the 'rocket' feature is enabled. ```bash $ cargo run --example rocket --features "rocket" ``` -------------------------------- ### Run Tiny HTTP Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating multipart usage with the tiny_http crate. Ensure the 'tiny_http' feature is enabled. ```bash $ cargo run --features tiny_http --example tiny_http ``` -------------------------------- ### Basic Adler-32 Hashing Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/simd-adler32/README.md Demonstrates the basic usage of the Adler32 hasher. Initialize the hasher, write data to it, and then finalize to get the hash value. ```rust use simd_adler32::Adler32; let mut adler = Adler32::new(); adler.write(b"rust is pretty cool, man"); let hash = adler.finish(); println!("{}", hash); // 1921255656 ``` -------------------------------- ### Get Elements By Class Name Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/www.upi.com/original.html Retrieves an array of elements that have a specific class name. Allows specifying a starting node and tag name for the search. ```javascript function getElementsByClass(searchClass, node, tag) { var classElements = new Array(); if (node == null) { node = document; } if (tag == null) { tag = '*'; } var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)"); for (i = 0, j = 0; i < elsLen; i++) { if (pattern.test(els[i].className)) { classElements[j] = els[i]; j++; } } return classElements; } ``` -------------------------------- ### jQuery Animation Prefilter Setup Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/www.upi.com/original.html Registers a prefilter function to customize or extend jQuery's animation behavior. Use this to hook into the animation process before it starts. ```javascript prefilter:function(e,t){t?lt.prefilters.unshift(e):lt.prefilters.push(e)}} ``` -------------------------------- ### Initialize Bid Adapter Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/wsvn.com/original.html Initializes the Conversant bid adapter, marking it as installed and adding it to the global `pbjs.installedModules` array. This is a standard setup procedure for bid adapters. ```javascript (0, a.dX)(l), window.pbjs.installedModules.push("conversantBidAdapter") ``` -------------------------------- ### Run Insecure Quinn Connection Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/quinn/examples/README.md Demonstrates establishing a QUIC connection while ignoring the server's certificate validation. Requires enabling a specific feature. ```text $ cargo run --example insecure_connection --features="rustls/dangerous_configuration" ``` -------------------------------- ### Enable All Tower Middleware Features Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/tower/README.md Add this to your Cargo.toml to enable all optional middleware provided by the Tower crate. This is useful for getting started with the full suite of Tower's capabilities. ```toml tower = { version = "0.5.1", features = ["full"] } ``` -------------------------------- ### Start Footer Ad Logic Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/www.wired.com/original.html Initiates the footer ad loading process, including version rendering, subscription setup, tool script appending, and PII/consent-based ad initialization. ```javascript function startFooter(){featureFlags.show_version&&renderVersion(),addDefaultSubscriptions(cnBus,featureFlags.bus_log),"info"===queryParameters.ao_tools&&append({src:`https://ad-tools.condenastdigital.com/ads-${queryParameters.ao_tools}/prod/index.js`,targ:document.head}),queryParameters.ap_noads||(hasPII()?onPIIDetected():(moatYieldIntelligence.load().then((()=>{window.cnBus.emit("ads.moat.yield-ready")})),til((()=>cns.pageContext),(()=>{shouldWaitForConsent()?onConsent(initAdsLibrary):initAdsLibrary()}))))} ``` -------------------------------- ### Basic errno Usage in Rust Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/errno/README.md Demonstrates how to get the current errno value, set it, extract the error code, and display a human-friendly error message. This example requires the standard library. ```rust extern crate errno; use errno::{Errno, errno, set_errno}; // Get the current value of errno let e = errno(); // Set the current value of errno set_errno(e); // Extract the error code as an i32 let code = e.0; // Display a human-friendly error message println!("Error {}: {}", code, e); ``` -------------------------------- ### Run Nickel Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating how to handle multipart uploads in nickel.rs. Ensure the 'nickel' feature is enabled. ```bash $ cargo run --example nickel --features nickel ``` -------------------------------- ### Run Rustls mio client example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/rustls/README.md Demonstrates how to run the `tlsclient-mio` example program to connect to a server. Use `--http` to specify a host for an HTTP request. ```bash $ cargo run --bin tlsclient-mio -- --http mozilla-modern.badssl.com ``` ```bash $ cargo run --bin tlsclient-mio -- --http expired.badssl.com ``` ```bash Run `cargo run --bin tlsclient-mio -- --help` for more options. ``` -------------------------------- ### RChunksMut Iterator Usage Source: https://github.com/brave/brave-core/blob/master/third_party/rust/chromium_crates_io/vendor/bitvec-v1/doc/slice/iter/RChunksMut.md This example demonstrates how to use the `rchunks_mut` method to create an iterator that yields mutable chunks of a bit-slice, starting from the end. It shows how to modify these chunks and verifies the final state of the original bit-slice. ```APIDOC ## `BitSlice::rchunks_mut` ### Description Creates an iterator that yields successive non-overlapping mutable chunks of a bit-slice, starting from the end. If the original bit-slice’s length is not evenly divided by the chunk width, then the final chunk will be the remainder, and will be shorter than requested. ### Method Signature ```rust fn rchunks_mut(&mut self, chunk_width: usize) -> RChunksMut<'_, T> ``` ### Parameters - `chunk_width` (usize): The desired width of each chunk. ### Returns An `RChunksMut` iterator yielding mutable slices of the bit-slice. ### Example ```rust use bitvec::prelude::*; let bits = bits![mut 0, 1, 0, 0, 0, 1, 1, 1]; let mut chunks = unsafe { bits.rchunks_mut(3).remove_alias() }; chunks.next().unwrap().fill(false); chunks.next().unwrap().fill(true); chunks.next().unwrap().copy_from_bitslice(bits![1, 0]); assert!(chunks.next().is_none()); assert_eq!(bits, bits![1, 0, 1, 1, 1, 0, 0, 0]); ``` ``` -------------------------------- ### Run CLI Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/codespan-reporting/README.md Execute this shell command to see the colored CLI output of the `codespan-reporting` example. This requires cloning the repository first. ```sh cargo run --example term ``` -------------------------------- ### Convert integer to String length using Conv trait Source: https://github.com/brave/brave-core/blob/master/third_party/rust/chromium_crates_io/vendor/wyz-v0_5/README.md Use the `Conv` trait to convert a value to a specified type, useful when type inference is difficult. This example converts a hex integer to a String and gets its length. ```rust use wyz::conv::Conv; let digits = 0xabcd.conv::().len(); ``` -------------------------------- ### Mocking URL Responses Inline Source: https://github.com/brave/brave-core/blob/master/components/brave_ads/core/internal/common/test/README.md Define mocked URL responses directly within the code. Filenames for inline mocks should start with a forward slash. This example shows how to mock a 404 Not Found and a 200 OK response. ```cpp const test::URLResponseMap url_responses = { "/foo/bar", { { net::HTTP_NOT_FOUND, "What we've got here is... failure to communicate" }, { net::HTTP_OK, "/response.json" } } }; test::MockUrlResponses(ads_client_mock_, url_responses); ``` -------------------------------- ### Run Hyper Server Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example demonstrating how to use multipart with a hyper::Server to intercept multipart requests. ```bash $ cargo run --example hyper_server ``` -------------------------------- ### Command-line Tool for Non-Cargo Setup Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/cxx/README.md Use the `cxxbridge-cmd` tool for non-Cargo build systems like Bazel or Buck. Install it via cargo and then use it to generate C++ header and source files from your Rust bridge definition. ```bash $ cargo install cxxbridge-cmd $ cxxbridge src/main.rs --header > path/to/mybridge.h $ cxxbridge src/main.rs > path/to/mybridge.cc ``` -------------------------------- ### Run Quinn HTTP/0.9 Server Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/quinn/examples/README.md Starts a server that listens for file requests using a simple HTTP-like protocol. Specify the directory to serve files from. ```text $ cargo run --example server ./ ``` -------------------------------- ### Run sysctl Example Source: https://github.com/brave/brave-core/blob/master/third_party/wasm/vendor/sysctl-0.5.5/README.md Execute one of the provided sysctl examples from the command line using Cargo. ```sh $ cargo run --example iterate ``` -------------------------------- ### Bellman-Ford Algorithm Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/petgraph/assets/guide/algodocs.md Demonstrates the usage of the `bellman_ford` algorithm in Rust for finding shortest paths in a graph with potential negative edge weights. It includes setup, execution, and assertions for both successful path computation and detection of negative cycles. ```rust use petgraph::Graph; use petgraph::algo::bellman_ford; use petgraph::prelude::*; let mut g = Graph::new(); let a = g.add_node(()); // node with no weight let b = g.add_node(()); let c = g.add_node(()); let d = g.add_node(()); let e = g.add_node(()); let f = g.add_node(()); g.extend_with_edges(&[ (0, 1, 2.0), (0, 3, 4.0), (1, 2, 1.0), (1, 5, 7.0), (2, 4, 5.0), (4, 5, 1.0), (3, 4, 1.0), ]); // Graph represented with the weight of each edge // 2 1 // a ----- b ----- c // | 4 | 7 | // d f | 5 // | 1 | 1 | // \------ e ------/ let path = bellman_ford(&g, a); assert!(path.is_ok()); let path = path.unwrap(); assert_eq!(path.distances, vec![ 0.0, 2.0, 3.0, 4.0, 5.0, 6.0]); assert_eq!(path.predecessors, vec![None, Some(a),Some(b),Some(a), Some(d), Some(e)]); // Node f (indice 5) can be reach from a with a path costing 6. // Predecessor of f is Some(e) which predecessor is Some(d) which predecessor is Some(a). // Thus the path from a to f is a <-> d <-> e <-> f let graph_with_neg_cycle = Graph::<(), f32, Undirected>::from_edges(&[ (0, 1, -2.0), (0, 3, -4.0), (1, 2, -1.0), (1, 5, -25.0), (2, 4, -5.0), (4, 5, -25.0), (3, 4, -1.0), ]); assert!(bellman_ford(&graph_with_neg_cycle, NodeIndex::new(0)).is_err()); ``` -------------------------------- ### Run Tokio-Rustls Server Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/tokio-rustls/README.md Command to execute the server example program. It requires the listening address, certificate file, and key file as arguments. ```sh cargo run --example server -- 127.0.0.1:8000 --cert certs/cert.pem --key certs/cert.key.pem ``` -------------------------------- ### Detect Time Zone Offset Conflicts Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/jiff/COMPARE.md Detects timezone offset conflicts by parsing a datetime string using different Time Zone Database versions. This example requires a custom parser setup and paths to specific tzdb versions. ```rust use jiff::{fmt::temporal::DateTimeParser, tz::{self, TimeZoneDatabase}}; // We use a custom parser with a default configuration because we need // to ask the parser to use a different time zone database than the // default. This can't be done via the nice `"...".parse()` API one // would typically use. static PARSER: DateTimeParser = DateTimeParser::new(); fn main() -> anyhow::Result<()> { // Open a version of tzdb from before Brazil announced its abolition // of daylight saving time. let tzdb2018 = TimeZoneDatabase::from_dir("path/to/tzdb-2018b")?; // Open the system tzdb. let tzdb = tz::db(); // Parse the same datetime string with the same parser, but using two // different versions of tzdb. let dt = "2020-01-15T12:00[America/Sao_Paulo]"; let zdt2018 = PARSER.parse_zoned_with(&tzdb2018, dt)?; let zdt = PARSER.parse_zoned_with(tzdb, dt)?; // Before DST was abolished, 2020-01-15 was in DST, which corresponded // to UTC offset -02. Since DST rules applied to datetimes in the // future, the 2018 version of tzdb would lead one to interpret // 2020-01-15 as being in DST. assert_eq!(zdt2018.offset(), tz::offset(-2)); // But DST was abolished in 2019, which means that 2020-01-15 was no // no longer in DST. So after a tzdb update, the same datetime as above // now has a different offset. assert_eq!(zdt.offset(), tz::offset(-3)); // So if you try to parse a datetime serialized from an older copy of // tzdb with a new copy of tzdb, you'll get an error under the default // configuration because of `OffsetConflict::Reject`. This would succeed if // you parsed it using tzdb2018! assert!(PARSER.parse_zoned_with(tzdb, zdt2018.to_string()).is_err()); Ok(()) } ``` -------------------------------- ### Run Hyper ReqBuilder Example Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/multipart/examples/README.md This command executes the example showcasing multipart usage with Hyper's new Client API and lazy writing capabilities. ```bash $ cargo run --example hyper_reqbuilder ``` -------------------------------- ### build.rs for Cargo-based CXX Setup Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/cxx/README.md Configure your build script to use `cxx_build::bridge` to generate and compile C++ code alongside your Rust project. This example specifies the main Rust file, a C++ source file, and the C++ standard to use. ```rust // build.rs fn main() { cxx_build::bridge("src/main.rs") // returns a cc::Build .file("src/demo.cc") .std("c++11") .compile("cxxbridge-demo"); println!("cargo:rerun-if-changed=src/demo.cc"); println!("cargo:rerun-if-changed=include/demo.h"); } ``` -------------------------------- ### Cookie Management Functions Source: https://github.com/brave/brave-core/blob/master/test/data/speedreader/rewriter/pages/news_pages/observer.com/original.html Provides utility functions for getting and setting cookies. `getCookieVal` retrieves the value of a cookie starting from a given offset, `getCookie` finds and returns the value of a specific cookie by name, and `hcPermutiveSetCookie` sets a cookie with specified name, data, and expiration. ```javascript function getCookieVal(offset) { var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) { endstr = document.cookie.length; } return unescape(document.cookie.substring(offset, endstr)); } ``` ```javascript function getCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) { return getCookieVal(j); } i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return ""; } ``` ```javascript function hcPermutiveSetCookie(name, data, expiration) { if (!expiration) { expiration = new Date(); // 1 year. expiration.setTime(expiration.getTime() + (5*365*24*60*60*1000)); } if (typeof data !== 'string') { data = JSON.stringify(data); } document.cookie = name + "=" + data + "; expires=" + expiration.toUTCString() + "; path=/"; } ``` -------------------------------- ### Display Help Message Source: https://github.com/brave/brave-core/blob/master/tools/crates/vendor/clap/examples/tutorial_builder/02_apps.md Run the application with the --help flag to display the generated help message, which includes usage, options, and descriptions. ```bash $ 02_apps --help Does awesome things Usage: 02_apps[EXE] --two --one Options: --two --one -h, --help Print help -V, --version Print version ```