Borrowing Recap
Lesson 20 of 48 in Coddy's Rust for Java Developers course.
Challenge
EasyImplement two APIs in archive.rs: pub fn prefix<'a>(text: &'a str, count: usize) -> &'a str returns at most count Unicode scalar values from the start, borrowing the same storage; and pub fn archive(text: String, count: usize) -> String consumes its string and returns that prefix followed by # and the original UTF-8 byte length. A count beyond the scalar count retains all text; zero retains none. Input is a nonnegative count on the first line and arbitrary text on the second, with no further newlines. solve calls archive and returns its result. archive must use the same prefix semantics as the public helper.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, archive.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod archive;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let data = String::from("犬abé");
assert_eq!(archive::prefix(&data, 2), "犬a");
assert_eq!(archive::prefix(&data, 2).as_ptr(), data.as_ptr());
assert_eq!(archive::prefix(&data, 0), "");
assert_eq!(archive::prefix(&data, 90), data.as_str());
assert_eq!(archive::archive(data, 3), "犬ab#7");
assert_eq!(archive::archive(String::new(), 9), "#0");
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
All lessons in Rust for Java Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler