Is Sorted Validates Ordered Input
is_sorted checks ascending order under PartialOrd and is_sorted_by_key validates a key such as a timestamp stays monotonic before the data is trusted.
Code
fn main() {
let ascending = [1, 3, 3, 7];
let descending = [9, 5, 5, 1];
let shuffled = [4, 1, 3];
// is_sorted:按 PartialOrd 检查升序(非严格,允许相邻相等)
println!("ascending: {}", ascending.is_sorted());
println!("descending: {}", descending.is_sorted());
println!("shuffled: {}", shuffled.is_sorted());
// is_sorted_by_key:按键函数校验,比如事件序号必须单调递增
let events = [(1, "boot"), (2, "ready"), (5, "serve")];
println!("events ordered: {}", events.is_sorted_by_key(|e| e.0));
// 校验失败时调用方决定拒绝,而不是静默处理乱序数据
let bad = [(1, "a"), (0, "b")];
println!("bad ordered: {}", bad.is_sorted_by_key(|e| e.0));
}How it works
Count the function main as the entire surface area of Is Sorted Validates Ordered Input.
Putting it to use
The demo output is labeled (ascending:, descending:, shuffled:), so every printed line maps back to its originating operation.
Core lines
let events = [(1, "boot"), (2, "ready"), (5, "serve")];
let bad = [(1, "a"), (0, "b")];
let descending = [9, 5, 5, 1];
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Is Sorted Validates Ordered Input print when run?
- Running the file directly is enough — expect labeled output lines such as `ascending:`, `descending:`, `shuffled:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.